Middleware that protects routes by checking for an authentication token.
import { NextRequest, NextResponse } from class=class="text-emerald-400">"text-emerald-400">'next/server'
const protectedPaths = [class=class="text-emerald-400">"text-emerald-400">'/dashboard', class=class="text-emerald-400">"text-emerald-400">'/settings', class=class="text-emerald-400">"text-emerald-400">'/profile']
const authPages = [class=class="text-emerald-400">"text-emerald-400">'/login', class=class="text-emerald-400">"text-emerald-400">'/register']
export function middleware(request: NextRequest) {
const { pathname } = request.nextUrl
const token = request.cookies.get(class=class="text-emerald-400">"text-emerald-400">'auth-token')?.value
const isProtected = protectedPaths.some(path => pathname.startsWith(path))
const isAuthPage = authPages.some(path => pathname.startsWith(path))
if (isProtected && !token) {
const loginUrl = new URL(class=class="text-emerald-400">"text-emerald-400">'/login', request.url)
loginUrl.searchParams.set(class=class="text-emerald-400">"text-emerald-400">'redirect', pathname)
return NextResponse.redirect(loginUrl)
}
if (isAuthPage && token) {
return NextResponse.redirect(new URL(class=class="text-emerald-400">"text-emerald-400">'/dashboard', request.url))
}
return NextResponse.next()
}
export const config = {
matcher: [class=class="text-emerald-400">"text-emerald-400">'/dashboard/:path*', class=class="text-emerald-400">"text-emerald-400">'/settings/:path*', class=class="text-emerald-400">"text-emerald-400">'/profile/:path*', class=class="text-emerald-400">"text-emerald-400">'/login', class=class="text-emerald-400">"text-emerald-400">'/register'],
}Save as middleware.ts in the project root. It redirects unauthenticated users to /login and redirects logged-in users away from auth pages. Customize protectedPaths for your app.
Let's discuss how we can bring your idea to life. From initial concept to production-ready product — we've got you covered.