Search code examples
expressnext.jsnext-auth

Using the JWT from Next-Auth to secure my server as well


I am setting up a next.js app and was planning on using next-auth's JWT strategy for auth. I understand how the workflow works to protect your next.js routes and api endpoints within your API folder, but I have a separate express.js server that handles an API to my database that this app will be using.

My question is, is there some way to send the JWT token to my express server along with any api calls, and hold the secret on that server as well to authenticate the session and give the user access to the api routes?

My thought was to do this either in a next-auth callback or just send the jwt token along when needed. I was just having trouble finding a way to view the full jwt server side. All of the server-side hooks next-auth provide parse out the data from the JWT.

Thanks for any insight.


Solution

  • Yes you can achieve this using the CredentialsProvider what you have to do is call your login endpoint to recive your JWT tokens once the user logged in and store them in next-auth session then you can access it using useSession() from anywhere to get the token you need and send it along with any REQUEST you want to send to your backend server.