Skip to content
GeeksSmith
intermediate 9 min read

Route Handlers, Edge Middleware, and Streaming Responses

Next.js Route Handlers provide custom HTTP endpoints using Web Request/Response APIs, while Edge Middleware intercepts incoming requests before cache or rendering to handle authentication, redirects, and header rewriting.

Why it matters in interviews

Modern frontend platforms require edge-level authentication, geolocation routing, token streaming, and reverse proxying without running heavy Node.js server instances. Mastering Middleware and Route Handlers is essential for full-stack frontend roles.

Visual & Interactive Explanation

Edge Middleware Request Interception Pipeline

Sequence & Data Exchange Flow

Browser
Edge Middleware
Next.js Cache
Server Component / API
#1
BrowserEdge Middleware
request

1. HTTP Request arrives with session cookie

#2
Edge MiddlewareEdge Middleware
compute

2. Verify JWT token signature at Edge (<5ms)

#3
Edge MiddlewareNext.js Cache
request

3. Rewrite request with x-user-id header

#4
Next.js CacheServer Component / API
compute

4. Forward to Server Component with pre-verified user claims

#5
Server Component / APIBrowser
response

5. Return HTML / Streaming response

Code Examples & Implementation

Edge Middleware Auth Interceptor & Header Rewrite
// middleware.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';

export function middleware(request: NextRequest) {
  const token = request.cookies.get('auth_token')?.value;
  const isAuthRoute = request.nextUrl.pathname.startsWith('/admin') || 
                      request.nextUrl.pathname.startsWith('/dashboard');

  if (isAuthRoute && !token) {
    const loginUrl = new URL('/login', request.url);
    loginUrl.searchParams.set('redirect', request.nextUrl.pathname);
    return NextResponse.redirect(loginUrl);
  }

  // Inject verified user metadata headers into downstream Server Components
  const requestHeaders = new Headers(request.headers);
  requestHeaders.set('x-forwarded-host', request.nextUrl.host);

  return NextResponse.next({
    request: {
      headers: requestHeaders,
    },
  });
}

export const config = {
  matcher: ['/dashboard/:path*', '/admin/:path*'],
};

Interview-Ready Answers

Route Handlers define HTTP endpoints (GET, POST, etc.) using standard Web Request/Response objects. Middleware runs at the Edge before route resolution to inspect cookies, headers, and perform fast redirects or rewrites.

Official Documentation & Specifications

Follow-up Questions & Deep Dives

Common Mistakes & Anti-Patterns

  • Using Node.js specific APIs (like fs or child_process) inside Middleware or Edge-runtime Route Handlers.
  • Forgetting to configure a strict matcher in middleware.ts, causing middleware to execute unnecessarily on static images and favicon files.
  • Attempting to set response cookies in Server Components instead of Server Actions or Route Handlers/Middleware.

Real-World Architectural Scenario

A SaaS dashboard needs A/B testing on pricing page variants without causing layout shift or flicker. How do you implement this in Next.js?

Rate Your Readiness

Rate how comfortably you can explain this in an interview to update your global readiness gauge:

Rate your confidence: