Search code examples
reactjsauthenticationnext.jsarchitecturenestjs

Does it make sense to create a webapp with a NestJS backend and Next.js frontend? + authentication


I am trying to create a web application in React with Next.js. I have experience with backend development in NestJS so I wanted to use it for this website as well. What I am still confused about is if it makes sense to separate it this way - React + Next.js frontend, NestJS backend.

In case it does make sense, I am confused about where user authentication should happen.

I have looked at NextAuth.js but I though that auth should be handled on the backend, not the frontend? On the backend I found password-js but then I don't know how it would connect to the frontend

I have looked at lots of websites about these frameworks but I get confused


Solution

  • Location

    I would say the location really depends on the scope of your project and your preference if you where making something relatively small then i would just use Next.js but if you where making something larger than maybe using an external server would be better.

    Authentication

    So Next.js is server side rendered so it can perform operations on the frontend and backend. So the way NextAuth.js works is it partly runs on the server side of Next.js and partly on the client side. It handles authentication and verification server side and interaction client side.

    By password-js i assume you mean passport-js as I can't find a library with that name. So there are a few ways to handle authentication using passport.js one way would be to use a JWT token which is a unique base64 encoded token that contains the user id and maybe some other data (Do note that any info in the JWT token is not encrypted just signed. So all data inside is public) it is signed with a private key on the server and when logging in it is verified by said server.

    The other way to handle authentication would be with a session token where you have a record in your DB with the session token (Which is basically a random ID) and probably some other info like an expiration date. This session token can then be provided to the frontend when logging in and user later when an action needs authentication on the server by checking that the record exists in the DB.

    The main advantage of the session token being that it is generally considered more secure because it can be revoked at any time where in comparison you can set an expiration date for a JWT but you can't revoke the token which can be an issue if say an account get's compromised there would be no way to revoke that token until it expires. Do note that passport.js supports these methods internally and you don't have to reimplement them you might want to take a look at https://www.passportjs.org/tutorials/password/session/ and this https://stytch.com/blog/jwts-vs-sessions-which-is-right-for-you/ for a more in depth comparison of JWTs vs Sessions.