Authentication in a Next.js app
Auth is where people mess up most, and where it costs the most. Sessions or JWT, where to store the token, where to put the checks: here's the authentication foundation I build, simple and solid.
Auth is where people mess up most, and where it costs the most. Sessions or JWT, where to store the token, where to put the checks: here's the authentication foundation I build, simple and solid.
Two ways to remember a user is logged in. The debate is eternal; in practice the choice is simple for a typical SaaS.
By default, for a SaaS, I go with sessions: being able to log a user out immediately beats the stateless elegance of JWT.
Middleware protects groups of routes at once (redirect if no session). But it doesn’t replace the check in each API route: middleware guards the door, the route guards the safe.
Never rely on middleware alone for data security: every route must re-check session AND resource ownership. That’s the IDOR flaw from the basic security holes.
Login rate limiting has its own article: rate limiting and API protection.
Solid auth isn't complicated, it's rigorous: revocable sessions for a SaaS, token in an httpOnly cookie, checks in every route and not just middleware, hashed passwords. Don't reinvent the wheel on OAuth — but understand every piece.
Auth.js docs ↗