#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

  1. Create middleware.ts.
  2. Log request.nextUrl.pathname to the console.
  3. Visit different pages and watch the server terminal.
  4. Implement a redirect: If the user visits /secret, redirect them to /.

See you tomorrow for Redirection (Server-side)! πŸ”€