Skip to content

Module 6: Middleware & Deployment

🌍 Module 6: Middleware & Deployment

In this module, we move from centralized server deployments and manual JWT middleware to the Edge Runtime.

🏗️ 1. The Mechanic: Centralized Middleware

In a traditional Node/Express app, middleware runs on your main server. If your server is in New York and your user is in Tokyo, the authentication check must travel around the world.

The Manual Pattern:

const protect = (req, res, next) => {
  const token = req.cookies.jwt;
  if (!token) return res.redirect('/login');
  // Verification happens on the central server
  next();
};

🏗️ 2. The Abstraction: Edge Middleware

Next.js Middleware runs on the “Edge” (thousands of servers globally). It executes before the request even reaches your main server, providing instant redirects and security checks.

The Next.js Way:

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

export function middleware(request) {
  const token = request.cookies.get('session');
  if (!token && request.nextUrl.pathname.startsWith('/dashboard')) {
    // This redirect happens at the user's nearest data center!
    return NextResponse.redirect(new URL('/login', request.url));
  }
}

🏗️ 3. Deployment: Incremental Static Regeneration (ISR)

Next.js allows you to update static pages after you’ve deployed, without a full rebuild.

The Code:

// Re-generate this static page every 60 seconds
export const revalidate = 60; 

export default async function Page() {
  const data = await db.post.findMany();
  return <PostList posts={data} />;
}

🧪 Professor’s Challenge: Deployment Strategy

Task:

  1. Research Partial Prerendering (PPR).
  2. Try to explain how it combines a static shell with dynamic Server Components.
  3. Deploy a test app to Vercel and notice the “Vercel-Specific” optimizations like Automatic Image Optimization.