authenticationnext.jsjwtnestjsnextjs-api-router

NestJS + NextJS for Authentication. New Architecture?


I'm new to NestJS and I'm trying to create a JWT-based authentication system. I want to generate a JWT token and manage it on the server side. I'm using Next.js on the frontend, so I was wondering if I could use Next.js API routes to protect my NestJS API endpoints while also handling the JWT token generated by the NestJS API. Would this approach be overengineering things? My main purpose is to hide the JWT/User Token from the client side. Appreciate any help! 🙏


Solution

  • I don't know anything about Next.js API routes, but if you're just after an efficient / secure / best-practice approach, then my guess is that you don't need to worry about hiding it in the frontend or anything like that.

    NestJS backend has a lot of built-in support for securing your endpoints. You can define different types of AuthGuards, and use/apply them either individually to whichever of your endpoints that need them (by just inserting the appropriate decorator above each of your controller routes), or you can set it up to apply the guard globally (to protect all endpoints, in which case you won't need to specify the guard-decorator each time).

    I remember working through this excellent tutorial video on the subject some time ago (Vlad has a couple of videos related to the JWT in NestJS topic): https://www.youtube.com/watch?v=uAKzFhE3rxU&t=5086s

    Also as a reminder: JWT payloads should be minimal and is never meant to keep really sensitive info in them. You can also use HttpOnly cookies in your frontend for a slightly more secure way of storing the tokens (where JavaScript is unable to access them)