Script Valley
Next.js: Full-Stack React Applications
Authentication with NextAuth.jsLesson 5.1

How to set up NextAuth.js v5 in a Next.js App Router project

Auth.js v5, auth() function, providers, AUTH_SECRET, session strategy, route handler setup, auth.config.ts pattern

Installing Auth.js v5

Auth.js v5 (formerly NextAuth.js) is the standard auth library for Next.js. Install it:

npm install next-auth@beta
npx auth secret  # Generates AUTH_SECRET in .env

Configuration Files

// auth.config.ts (edge-compatible, no Node.js APIs)
import type { NextAuthConfig } from 'next-auth'

export const authConfig: NextAuthConfig = {
  pages: {
    signIn: '/login',
  },
  callbacks: {
    authorized({ auth, request: { nextUrl } }) {
      const isLoggedIn = !!auth?.user
      const isOnDashboard = nextUrl.pathname.startsWith('/dashboard')
      if (isOnDashboard) return isLoggedIn
      return true
    },
  },
  providers: [],
}
// auth.ts (full Node.js โ€” has Prisma/DB access)
import NextAuth from 'next-auth'
import { authConfig } from './auth.config'
import GitHub from 'next-auth/providers/github'

export const { auth, signIn, signOut, handlers } = NextAuth({
  ...authConfig,
  providers: [GitHub],
})
// app/api/auth/[...nextauth]/route.ts
import { handlers } from '@/auth'
export const { GET, POST } = handlers

Environment Variables

AUTH_SECRET=your-generated-secret
AUTH_GITHUB_ID=your-github-oauth-app-id
AUTH_GITHUB_SECRET=your-github-oauth-app-secret

The split between auth.config.ts and auth.ts is required because middleware runs in the Edge Runtime, which cannot use Node.js APIs like Prisma. Put edge-safe logic in auth.config.ts and import it in both auth.ts and middleware.ts.

Up next

How to add OAuth providers to NextAuth.js (GitHub, Google)

Sign in to track progress

How to set up NextAuth.js v5 in a Next.js App Router project โ€” Authentication with NextAuth.js โ€” Next.js: Full-Stack React Applications โ€” Script Valley โ€” Script Valley