#nextjs
#middleware
#edge
#auth
Day 19 β Middleware: The Gatekeeper
π§ Day 19 β Middleware: The Gatekeeper
Zero to Hero β Hands-on Next.js Tutorial
Middleware allows you to run code before a request is completed.
It lives in src/middleware.ts (same level as app).
It runs on the Edge (a very limited, fast runtime).
- β Can: Read cookies, headers, redirect, rewrite URLs.
- β Cannot: Access Node.js APIs (e.g.,
fs), connect directly to most SQL databases (unless via HTTP).
π¦ 1. Basic Structure
// src/middleware.ts
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
export function middleware(request: NextRequest) {
return NextResponse.next()
}
π© 2. Matching Paths
You donβt want middleware running on static assets (images, CSS). Use a matcher config.
export const config = {
matcher: [
/*
* Match all request paths except for the ones starting with:
* - api (API routes)
* - _next/static (static files)
* - _next/image (image optimization files)
* - favicon.ico (favicon file)
*/
'/((?!api|_next/static|_next/image|favicon.ico).*)',
],
}
π§ 3. Authentication Example
This is the #1 use case. Redirect users if they arenβt logged in.
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
export function middleware(request: NextRequest) {
// 1. Check for token
const token = request.cookies.get('auth_token')
// 2. Define protected routes
if (request.nextUrl.pathname.startsWith('/dashboard')) {
if (!token) {
// 3. Redirect to login
return NextResponse.redirect(new URL('/login', request.url))
}
}
return NextResponse.next()
}
π₯ 4. Challenge: Geo-Blocking
Since middleware receives the request, it can access the userβs location (if deployed on Vercel/Cloudflare).
export function middleware(req: NextRequest) {
const country = req.geo?.country || 'US';
if (country === 'KP') { // Block North Korea
return new NextResponse('Access Denied', { status: 403 });
}
return NextResponse.next();
}
π§ͺ Challenge: Day 19
- Create
middleware.ts. - Log
request.nextUrl.pathnameto the console. - Visit different pages and watch the server terminal.
- Implement a redirect: If the user visits
/secret, redirect them to/.
See you tomorrow for Redirection (Server-side)! π