WhoBuilt

Next.js App Router Authentication

Feb 5, 2024· 12 min· 354K views·Watch on YouTube

Lee Roberson, a developer at Vercel, explains Next.js App Router authentication and compares a basic cookie session with NextAuth.js.

Build a basic session

Lee starts with a minimal Next.js example that reads the session in an async server component and uses server actions for login and logout. The login function reads form data, looks up user information, creates a session, and stores it in an HTTP-only cookie.

Sign and refresh the session

The example signs a JWT with the Jose library, using a secret key that should be kept in an environment variable. Middleware checks for the session cookie, verifies it, and refreshes its expiration. The demo sets the cookie to expire after 10 seconds to show how expiration and renewal work.

Read and remove session data

The `getSession` function reads the session cookie and decrypts it to return session information. Logging out deletes the cookie. Lee describes this as a minimal starting point that developers can extend.

Use NextAuth.js with GitHub

Lee then shows a NextAuth.js setup using the GitHub provider, catch-all route handlers, and the `auth`, `signIn`, and `signOut` functions. The demo creates a session token, callback URL, and CSRF token, while middleware refreshes the session and uses a route matcher to skip static assets.

Explore broader auth needs

Lee points to Next.js documentation covering authorization and protecting server actions and route handlers. He also mentions database sessions and examples using Clerk, Lucia, Auth0, and Supabase.

Takeaways

  • Keep signing secrets in environment variables and mark session cookies HTTP-only.
  • Verify and refresh sessions in middleware when using rolling expiration.
  • Read session data on the server, and clear the cookie to log out.
  • Consider an auth library such as NextAuth.js when you need provider integrations and built-in security features.
  • Plan for authorization as well as authentication, especially when protecting server actions and route handlers.

Mentioned in this talk

Search inside this talk

What was claimed 7

Related talks

Next.js App Router Authentication · WhoBuilt