5

I'm using Express routes with Next, on the example below /a should be accessible by authorised people, while /b is public.

... other imports...
const app = next({ isDev })
const handle = app.getRequestHandler()

async function isAuth(req, res, next) {
  const token = req.header('x-Auth-Token');
  if (!token) return res.status(401).send('Access denied. No token provided.');

  req.user = 'Connected!';
  next();
}

app.prepare().then(() => {
  const server = express()

  server.get('/a', isAuth, async (req, res) => {
    return app.render(req, res, '/a', req.query)
  })

  server.get('/b', async (req, res) => {
    return app.render(req, res, '/b', req.query)
  })

  server.all('*', (req, res) => {
    return handle(req, res)
  })

  server.listen(port, err => {
    if (err) throw err
    console.log(`> Ready on http://localhost:${port}`)
  })
})

Pretty easy and straightforward, for now I'm correctly getting my access denied on the /a using the url bar of the browser except when I use a <Link href="/a"> from my /b page. Then the page shows the hidden content and my access has not been checked... why? How can I resolve this issue?

This issue can be replicated using this Github link, you will just need to add the isAuth example as I did on the example above.

0

1 Answer 1

3

That is part of how the Next.JS Link works. It already pre-fetches the sources for the upcoming site, without ever fetching against the real endpoint, thus you are required to implement both frontend and backend checks for your current situation.

For further information feel free to follow this discussion within Next.JS Github Issue: Github NextJs Restricted Links. It clearly explains how to deal with such a situation.

Sign up to request clarification or add additional context in comments.

2 Comments

You can just use an HOC component to check if the cookie exist
@NicolòCozzani Definitely there's more than one way to tackle this problem, but I just pointed out that it definitely requires a frontend check as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.