Crash Courses · Masters
Middleware & Authentication
Protect routes and redirect users with middleware and Next.js auth patterns.
11 min read+175 XP on completionCert: Next.js Crash Course
Tap any word in the text below to start reading from there.
Middleware & Authentication
Middleware runs at the CDN edge before every matching request — ideal for auth guards, redirects, and A/B testing.
Basic Middleware
// middleware.ts (root of project)
import { NextRequest, NextResponse } from 'next/server'
export function middleware(req: NextRequest) {
const session = req.cookies.get('session')?.value
const isProtected = req.nextUrl.pathname.startsWith('/dashboard')
if (isProtected && !session) {
const loginUrl = new URL('/login', req.url)
loginUrl.searchParams.set('callbackUrl', req.nextUrl.pathname)
return NextResponse.redirect(loginUrl)
}
return NextResponse.next()
}
export const config = {
matcher: [
'/((?!api|_next/static|_next/image|favicon.ico).*)',
],
}Route-Specific Guards
export function middleware(req: NextRequest) {
const { pathname } = req.nextUrl
// Allow public routes
if (
pathname.startsWith('/login') ||
pathname.startsWith('/register') ||
pathname.startsWith('/api/auth')
) {
return NextResponse.next()
}
const token = req.cookies.get('auth-token')?.value
if (!token) {
return NextResponse.redirect(new URL('/login', req.url))
}
// Add user id to headers so server components can read it
const res = NextResponse.next()
res.headers.set('x-user-token', token)
return res
}Reading Auth in Server Components
import { cookies } from 'next/headers'
import { redirect } from 'next/navigation'
async function getSession() {
const cookieStore = await cookies()
const token = cookieStore.get('auth-token')?.value
if (!token) redirect('/login')
return verifyToken(token)
}
export default async function DashboardPage() {
const user = await getSession()
return <Dashboard user={user} />
}Reading progress
0% read
In this module
middleware.ts
Edge Runtime
config.matcher
NextResponse.redirect
0%