Middleware in Next.js allows you to run code before a request is completed. Perfect for authentication, redirects, and more.

Creating Middleware

// middleware.ts
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'

export function middleware(request: NextRequest) {
  if (request.nextUrl.pathname.startsWith('/admin')) {
    return NextResponse.redirect(new URL('/login', request.url))
  }
}

export const config = {
  matcher: '/admin/:path*'
}

Common Use Cases

  • Authentication checks
  • Redirects and rewrites
  • A/B testing
  • Bot protection