Technologies

Next.js Authentication Development

Authentication in Next.js has to account for both server and client components, middleware, and API routes all needing to know who the current user is — the App Router's model changes how that state gets checked compared to the older Pages Router pattern.

I implement authentication using session cookies validated in middleware and server components, with Supabase Auth as a common backend, or a custom Node.js session layer where the project needs full control.

What a Solid Setup Includes

  • checkSession validation in middleware, so protected routes redirect before any page code runs
  • checkServer components that can read the current user without a client-side round trip
  • checkRole-based access control for routes and API endpoints
  • checkSecure, httpOnly session cookies rather than tokens stored in localStorage
  • checkPassword reset, email verification, and OAuth provider flows as needed

Protecting Routes

Next.js middleware runs before a request reaches a page, which makes it the right place to check session validity and redirect unauthenticated users — cheaper and more secure than checking auth state inside the page component after it's already started rendering.

Common Mistakes

  • arrow_rightStoring auth tokens in localStorage, which is readable by any script on the page and vulnerable to XSS
  • arrow_rightChecking authentication only on the client, leaving the server-rendered HTML briefly exposing content it shouldn't
  • arrow_rightNot validating sessions in API routes independently, relying only on the frontend to hide unauthorized actions

Frequently Asked Questions

Do you use NextAuth.js or build custom authentication?add

It depends on the project — NextAuth (Auth.js) is a solid default for standard email/password and OAuth flows. For projects already using Supabase, its built-in auth is usually simpler since it's already wired into the same database and row-level security.

How do you protect API routes?add

Every API route independently validates the session — never assuming a request only came from an authenticated page, since API routes can be called directly regardless of what the frontend hides.

Can this support role-based permissions?add

Yes — roles are checked both in middleware (to gate entire route sections) and at the API level (to gate specific actions), so permission checks don't rely solely on hiding UI elements.

NEED THIS FOR YOUR PROJECT?

I'm currently available for freelance and contract work. Check availability and engagement options, or reach out directly to discuss scope.