Reputation: 722
I would like my NEXTJS project to check the cookie headers (httponly) and validate the JWT server side. I would like to respond with a 302 redirect to /login in case the user is not logged in. Where would this logic normally go? I tried putting it in _app.js
's getInitialProps
, but that seems to break things horribly except for the intitial page-render. Moving the logic to _document.js
's getInitialProps
seems to do the trick, but I'm not sure that's good practice? Where would you put it, if one of the requirements is that no html/js/css response should be given unless authenticated? thanks in advance! :)
Upvotes: 3
Views: 1700
Reputation: 795
I think you could reference this https://github.com/vercel/next.js/tree/canary/examples/with-iron-session and modify a little:
/api/login
and/or /api/user
. Next.js won't bundle your JWT decoder in the client sideuserUser
- https://github.com/vercel/next.js/blob/canary/examples/with-iron-session/pages/profile-sg.js) or SSR (getServerSideProps
- https://github.com/vercel/next.js/blob/canary/examples/with-iron-session/pages/profile-ssr.js) depends on your needCaution: This is an official example and said to be using best practices for authentication in Next.js.
I met a similar one in few real world examples, client request to authentication server and get a JWT token, then you pass this token into Next.js req.cookie for session handling. What I don't like is we have to provide the secret for decoding JWT in the server side of Next.js
Upvotes: 2