Reputation: 5578
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.
Upvotes: 5
Views: 973
Reputation: 2435
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.
Upvotes: 3