2

I really don't understand, why it is so complex to build authentication and persisting in session with Node.js.

I'm having trouble with session persistance, that is described here.

Maybe, I something don't understand...

So, in an SPA, when a browser making fetch with POST method from UI, Passport authenticates and saves session in DB (as I've setup).

What's next?

How to tell React front-end (browser, server…), that It should apply newly created cookie and use it for all subsequent requests for HMR, GraphQL and other stuff?

What I have is all subsequent requests to server referring old cookie (not created one on successful authentication) and that correct one will never looked up…

Some explanation will be greatly appreciated.

Thank You.

PS: Still looking for simple working examples of authentication with latest Next.js, Express and Passport. I'm stuck with this problem on a week…

AntonAL
  • 16,692
  • 21
  • 80
  • 114

1 Answers1

0

You can make a request to the endpoint of express which is going to return you the information... for this you can use Axios, when it response you can set the cookie with something like this:

document.cookie = `id_token=${token}; expires=Thu, 18 Dec 2020 12:00:00 UTC`

In my case I set a token because I use JWT, when the cookie is set, you can request it on the server side using cookie-parser, so, when you are going to verify is the user is logged you can check if the cookie exists on the server (Next.js) and render the template, otherwise you can redirect to other view... something like this:

server.get('/profile', (req, res) => {
  const actualPage = '/profile';
  const logged = req.cookies['id_token']
  if (logged) {
    return app.render(req, res, actualPage)
  }
  return res.redirect('/')
})

If you want to see the complete example, check this repo