πŸŽ‰ 75% of content is free forever β€” Unlock Premium from $10/mo β†’
CW
Search courses…
πŸ’Ό Servicesℹ️ Aboutβœ‰οΈ ContactView Pricing Plansfrom $10

Middleware

Next.js Backend🟒 Free Lesson

Advertisement

Middleware

Request interception, authentication, redirects, headers, and edge runtime.

Overview

Middleware runs before a request is completed, enabling authentication and request modification.

Key Concepts

  • Edge Runtime β€” Runs at the edge for low latency
  • Request/Response β€” Modify headers, cookies, redirect
  • Authentication β€” Check tokens before route access
  • A/B Testing β€” Route users to different variants
  • Geolocation β€” Access user location data

Code Examples

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

export function middleware(request) {
  const token = request.cookies.get('token');
  const isAuthenticated = !!token;

  // Protect dashboard routes
  if (request.nextUrl.pathname.startsWith('/dashboard') && !isAuthenticated) {
    return NextResponse.redirect(new URL('/login', request.url));
  }

  // Add custom headers
  const response = NextResponse.next();
  response.headers.set('x-user-id', token?.value || 'anonymous');

  return response;
}

// Advanced middleware with geolocation
export function middleware(request) {
  const country = request.geo?.country;
  
  // Redirect based on location
  if (request.nextUrl.pathname === '/') {
    if (country === 'US') {
      return NextResponse.redirect(new URL('/en', request.url));
    }
    return NextResponse.redirect(new URL('/es', request.url));
  }

  return NextResponse.next();
}

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

Practice

Implement authentication middleware with role-based access control.

⭐

Premium Content

Middleware

Unlock this lesson and 900+ advanced tutorials with a Premium plan.

🎯End-to-end Projects
πŸ’ΌInterview Prep
πŸ“œCertificates
🀝Community Access

Already a member? Log in

Need Expert Next.js Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement