nextjs route middleware for authentication

不羁岁月 提交于 2020-06-24 03:59:17

问题


I'm trying to figure out an appropriate way of doing authentication, which I know is a touchy subject on the GitHub issue page.

My authentication is simple. I store a JWT token in the session. I send it to a different server for approval. If I get back true, we keep going, if I get back false, it clears the session and puts sends them to the main page.

In my server.js file I have the following (note- I am using the example from nextjs learn and just adding isAuthenticated):

function isAuthenticated(req, res, next) {
  //checks go here

  //if (req.user.authenticated)
   // return next();

  // IF A USER ISN'T LOGGED IN, THEN REDIRECT THEM SOMEWHERE
  res.redirect('/');
}

server.get('/p/:id', isAuthenticated, (req, res) => {
  const actualPage = '/post'
  const queryParams = { id: req.params.id }
  app.render(req, res, actualPage, queryParams)
})

This works as designed. If I refresh the page /p/123, it will redirect to the /. However, if I go there via a next/link href, it doesn't. Which I believe is because it's not using express at this point but next's custom routing.

Is there a way I can bake in a check for every single next/link that doesn't go through express so that I can make sure the user is logged in?


回答1:


Tim from the next chat helped me solve this. Solution can be found here but I will quote him so you all can see:

  • You can do the check in _app.js getInitialProps and redirect like this
  • Example of how to use it
  • _app.js documentation

I've also created an example skeleton template you can take a look at.



来源:https://stackoverflow.com/questions/51426252/nextjs-route-middleware-for-authentication

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!