Next.js course ยท Module 2: Routing and Layouts

Middleware and Request Interception

17 min read ยท
In this lesson15

At the heart of the Quantum Metropolis lies an advanced access control and redirect system known as the Quantum Gateway. This system monitors every access attempt to various city zones, verifies permissions, redirects to appropriate points, and modifies travel routes in real time. It's an extremely important infrastructure element that ensures both security and traffic optimization throughout the city.

In the world of Next.js 16, Proxy (called Middleware up to version 15) plays a similar role - a powerful mechanism that allows intercepting and modifying HTTP requests before they are handled by a page or API, enabling the implementation of features like authorization, redirects, or response modifications.

What is Proxy (formerly Middleware) in Next.js 16?

Proxy is a function that is executed before a request is handled by a page or API route. It operates between the client request and server response, providing the ability to:

  • Execute code before loading the page
  • Modify the request object
  • Modify the response object
  • Redirect the user
  • Reject requests
  • Add HTTP headers
  • Modify cookies

Basic Middleware Structure

In Next.js 16, you put this code in a proxy.ts (or proxy.js) file in the project root directory (next to app or pages, or inside src if your project uses it). Up to version 15 the file was called middleware.ts and the exported function middleware: Next.js 16 renamed both, but the logic stayed the same. The old file still works, but it is deprecated, and the proxy always runs in the Node.js runtime.

// proxy.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';

// The proxy function is executed before every request
export function proxy(request: NextRequest) {
  // Here we can implement our logic
  console.log('Proxy executed for:', request.nextUrl.pathname);

  // We can modify the response object
  return NextResponse.next();
}

// Optionally, we can limit which routes the proxy runs for
export const config = {
  matcher: '/api/:path*',
};

Available Middleware Operations

1. Redirects and Rewrites

Just as in the Quantum Metropolis, where security gates can automatically redirect unauthorized visitors to checkpoints, middleware in Next.js allows redirecting requests:

// proxy.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';

export function proxy(request: NextRequest) {
  // Check if the user is trying to access the admin zone
  if (request.nextUrl.pathname.startsWith('/admin')) {
    // Check if the user is logged in (e.g., by checking a cookie)
    const isLoggedIn = request.cookies.has('auth-token');

    if (!isLoggedIn) {
      // Redirect unauthenticated users to the login page
      const loginUrl = new URL('/login', request.url);
      // Add the original URL as a parameter so we can return after login
      loginUrl.searchParams.set('from', request.nextUrl.pathname);
      return NextResponse.redirect(loginUrl);
    }
  }

  // Otherwise, continue with normal request processing
  return NextResponse.next();
}

2. Modifying Request or Response Headers

We can also modify headers, just as the Quantum Gateway can add special identifiers to transport tickets:

// proxy.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';

export function proxy(request: NextRequest) {
  // Get the original response
  const response = NextResponse.next();

  // Add custom headers to the response
  response.headers.set('x-quantum-security', 'enabled');
  response.headers.set('x-quantum-gateway-version', '15.0.1');

  // Add Content Security Policy (CSP)
  response.headers.set(
    'Content-Security-Policy',
    "default-src 'self'; script-src 'self' 'unsafe-eval' 'unsafe-inline' quantum-cdn.example.com;"
  );

  return response;
}

3. Manipulating Cookies

Middleware can also manipulate cookies, which is useful for session management:

// proxy.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';

export function proxy(request: NextRequest) {
  const response = NextResponse.next();

  // Read cookie value
  const theme = request.cookies.get('theme')?.value;

  // Set a new cookie
  response.cookies.set('last-visit', new Date().toISOString());

  // Change existing cookie value
  if (theme === 'dark') {
    response.cookies.set('theme-version', 'dark-v2');
  }

  // Delete cookie
  if (request.nextUrl.pathname === '/logout') {
    response.cookies.delete('auth-token');
  }

  return response;
}

4. Rewrite - URL Substitution Without Changing the Visible Address

Rewrite allows internally substituting the URL without changing the address visible to the user:

// proxy.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';

export function proxy(request: NextRequest) {
  // Example: internally redirect all requests from /docs to /documentation
  // The address in the browser bar remains /docs
  if (request.nextUrl.pathname.startsWith('/docs')) {
    const url = request.nextUrl.clone();
    url.pathname = url.pathname.replace(/^\/docs/, '/documentation');
    return NextResponse.rewrite(url);
  }

  return NextResponse.next();
}

Implementing Middleware for the Quantum Voyages Application

Let's prepare comprehensive middleware for our Quantum Voyages application that will handle:

  1. Authorization for protected zones
  2. Internationalization and language detection
  3. Tracking and analytics
// proxy.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import { verifyAuthToken } from './lib/auth';

// List of supported languages
const SUPPORTED_LOCALES = ['pl', 'en', 'de', 'fr'];
// Default language
const DEFAULT_LOCALE = 'pl';
// Paths requiring authorization
const PROTECTED_PATHS = ['/dashboard', '/account', '/bookings'];
// Admin paths requiring admin permissions
const ADMIN_PATHS = ['/admin'];

export async function proxy(request: NextRequest) {
  const { pathname } = request.nextUrl;

  // 1. Handle localization and internationalization
  const pathnameHasLocale = SUPPORTED_LOCALES.some(
    locale => pathname.startsWith(`/${locale}/`) || pathname === `/${locale}`
  );

  // If the path doesn't contain a language code yet, redirect and add the code
  if (!pathnameHasLocale) {
    // Attempt to detect the user's preferred language
    const preferredLocale = getPreferredLocale(request);
    const url = new URL(request.url);
    url.pathname = `/${preferredLocale}${pathname}`;
    return NextResponse.redirect(url);
  }

  // Extract the language code from the path
  const locale = pathname.split('/')[1];

  // 2. Authorization for protected zones
  // Check if the path is protected
  if (isProtectedPath(pathname)) {
    const authToken = request.cookies.get('auth-token')?.value;

    // Verify the authorization token
    const authResult = await verifyAuthToken(authToken);

    // If the user is not logged in or the token is invalid
    if (!authResult.isValid) {
      const loginUrl = new URL(`/${locale}/login`, request.url);
      loginUrl.searchParams.set('returnTo', request.nextUrl.pathname);
      return NextResponse.redirect(loginUrl);
    }

    // Check admin permissions for administrative paths
    if (isAdminPath(pathname) && !authResult.isAdmin) {
      const accessDeniedUrl = new URL(`/${locale}/access-denied`, request.url);
      return NextResponse.redirect(accessDeniedUrl);
    }
  }

  // 3. Add analytics and security headers
  const response = NextResponse.next();

  // Add user info for analytics tools (no personal data)
  const visitorId = request.cookies.get('visitor-id')?.value || generateVisitorId();
  response.cookies.set('visitor-id', visitorId, {
    httpOnly: true,
    sameSite: 'strict',
    maxAge: 60 * 60 * 24 * 365 // 1 rok
  });

  // Security headers
  response.headers.set('X-Frame-Options', 'DENY');
  response.headers.set('X-Content-Type-Options', 'nosniff');
  response.headers.set('Referrer-Policy', 'strict-origin-when-cross-origin');

  return response;
}

// Helper functions

// Detecting the user's preferred language
function getPreferredLocale(request: NextRequest): string {
  // Check previously saved preferred language in cookie
  const savedLocale = request.cookies.get('preferred-locale')?.value;
  if (savedLocale && SUPPORTED_LOCALES.includes(savedLocale)) {
    return savedLocale;
  }

  // Check the Accept-Language header
  const acceptLanguage = request.headers.get('accept-language');
  if (acceptLanguage) {
    // Parse Accept-Language header and find the best match
    const userLocales = acceptLanguage.split(',')
      .map(item => {
        const [locale, priority = 'q=1.0'] = item.trim().split(';');
        const q = parseFloat(priority.replace('q=', '')) || 1.0;
        return { locale: locale.split('-')[0], q };
      })
      .sort((a, b) => b.q - a.q);

    // Find the first supported language
    for (const { locale } of userLocales) {
      if (SUPPORTED_LOCALES.includes(locale)) {
        return locale;
      }
    }
  }

  // Default language if preferences cannot be determined
  return DEFAULT_LOCALE;
}

// Check if the path is protected
function isProtectedPath(pathname: string): boolean {
  return PROTECTED_PATHS.some(path => {
    // Remove the language code from the path before comparison
    const pathWithoutLocale = pathname.split('/').slice(2).join('/');
    return `/${pathWithoutLocale}`.startsWith(path);
  });
}

// Check if the path is administrative
function isAdminPath(pathname: string): boolean {
  return ADMIN_PATHS.some(path => {
    // Remove the language code from the path before comparison
    const pathWithoutLocale = pathname.split('/').slice(2).join('/');
    return `/${pathWithoutLocale}`.startsWith(path);
  });
}

// Generate a unique ID for the visitor
function generateVisitorId(): string {
  return `${Date.now()}-${Math.random().toString(36).substring(2, 15)}`;
}

// Determine which paths the proxy will run for
export const config = {
  matcher: [
    // Match all paths
    '/((?!api|_next/static|_next/image|favicon.ico).*)',
  ],
};

Selective Middleware Execution with Matcher

Just as in the Quantum Metropolis, where not every movement requires a full security check, in Next.js 16 we can specify which paths the proxy will run for using the matcher configuration:

// proxy.ts
export const config = {
  matcher: [
    // Paths for which the proxy will run
    '/dashboard/:path*',
    '/api/:path*',
    '/((?!_next/static|_next/image|favicon.ico).*)',
  ],
};

Various matcher patterns are available:

  1. Exact matching: '/about'
  2. Matching with parameters: '/blog/:path'
  3. Matching with catch-all parameters: '/blog/:path*'
  4. Several paths at once: an array ['/dashboard/:path*', '/admin/:path*'] or a group in parentheses '/(dashboard|admin)/:path*'
  5. Negation matching: /((?!api|_next/static|_next/image|favicon.ico).*)

Implementing JWT Authorization with Middleware

In the Quantum Metropolis, resident identifiers are verified using advanced cryptographic technology. Let's implement a similar JWT authorization system in our application:

// proxy.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import { jwtVerify } from 'jose';

interface UserPayload {
  id: string;
  email: string;
  role: string;
  exp: number;
}

export async function proxy(request: NextRequest) {
  // Check if the path requires authorization
  if (request.nextUrl.pathname.startsWith('/dashboard') ||
      request.nextUrl.pathname.startsWith('/api/protected')) {

    // Get JWT token from cookie or Authorization header
    const authToken = request.cookies.get('auth-token')?.value ||
                     request.headers.get('Authorization')?.split(' ')[1];

    if (!authToken) {
      // No token - redirect to login
      return redirectToLogin(request);
    }

    try {
      // Verify JWT token
      const secretKey = new TextEncoder().encode(process.env.JWT_SECRET!);
      const { payload } = await jwtVerify<UserPayload>(authToken, secretKey);

      // Check if the token has expired
      const currentTime = Math.floor(Date.now() / 1000);
      if (payload.exp < currentTime) {
        // Token expired - redirect to login
        return redirectToLogin(request);
      }

      // Check admin permissions for administrative paths
      if (request.nextUrl.pathname.startsWith('/admin') && payload.role !== 'admin') {
        return NextResponse.json(
          { message: 'Insufficient permissions' },
          { status: 403 }
        );
      }

      // Add user info to headers for subsequent handlers
      const response = NextResponse.next();
      response.headers.set('x-user-id', payload.id);
      response.headers.set('x-user-role', payload.role);

      return response;
    } catch (error) {
      // Token verification error - redirect to login
      return redirectToLogin(request);
    }
  }

  return NextResponse.next();
}

// Function that redirects to login
function redirectToLogin(request: NextRequest) {
  const loginUrl = new URL('/login', request.url);
  loginUrl.searchParams.set('returnTo', request.nextUrl.pathname);
  return NextResponse.redirect(loginUrl);
}

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

Implementing Theme Switching with Middleware

Quantum City offers its residents the ability to customize the appearance of city interfaces. Let's implement a similar system for switching between light and dark themes:

// proxy.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';

export function proxy(request: NextRequest) {
  // Get preferred theme
  const theme = request.cookies.get('theme')?.value || 'light';

  // Create response
  const response = NextResponse.next();

  // Set theme preference variable as a cookie
  response.cookies.set('theme', theme, {
    maxAge: 60 * 60 * 24 * 365, // valid for one year
    path: '/',
  });

  // Add a custom header that can be read by the client
  response.headers.set('x-theme', theme);

  return response;
}

export const config = {
  matcher: '/((?!api|_next/static|_next/image|favicon.ico).*)',
};

Handling Multiple Domains and Subdomains with Middleware

In the Quantum Metropolis, different districts can have their own access systems. Similarly in Next.js, we can handle different domains and subdomains:

// proxy.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';

export function proxy(request: NextRequest) {
  const { pathname, hostname } = request.nextUrl;

  // Handle different subdomains
  if (hostname === 'admin.quantumvoyages.com') {
    // Redirect all requests to the admin panel
    const url = new URL('/admin' + pathname, request.url);
    return NextResponse.rewrite(url);
  }

  if (hostname === 'api.quantumvoyages.com') {
    // Redirect requests to the API
    const url = new URL('/api' + pathname, request.url);
    return NextResponse.rewrite(url);
  }

  if (hostname.startsWith('user-')) {
    // Handle user subdomains (e.g., user-john.quantumvoyages.com)
    const username = hostname.replace('user-', '').split('.')[0];
    const url = new URL(`/profile/${username}${pathname}`, request.url);
    return NextResponse.rewrite(url);
  }

  return NextResponse.next();
}

export const config = {
  matcher: '/((?!_next/static|_next/image|favicon.ico).*)',
};

Caching and Response Header Modification

In the Quantum Metropolis, the Gateway system optimizes data flow through its systems. Similarly, we can optimize our application:

// proxy.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';

export function proxy(request: NextRequest) {
  const response = NextResponse.next();

  // Set caching headers for static assets
  if (request.nextUrl.pathname.match(/\.(jpg|jpeg|png|webp|svg|gif|ico)$/)) {
    response.headers.set('Cache-Control', 'public, max-age=31536000, immutable');
  }

  // Set caching headers for HTML pages
  else if (!request.nextUrl.pathname.startsWith('/api/')) {
    response.headers.set('Cache-Control', 'public, max-age=300, s-maxage=3600');
  }

  // Add security headers
  response.headers.set('Strict-Transport-Security', 'max-age=63072000');
  response.headers.set('X-Content-Type-Options', 'nosniff');
  response.headers.set('X-Frame-Options', 'DENY');
  response.headers.set('X-XSS-Protection', '1; mode=block');

  return response;
}

export const config = {
  matcher: '/((?!_next/static|_next/image|favicon.ico).*)',
};

Implementing Geolocation and Content Personalization

The Quantum Metropolis adjusts available services based on resident locations. Let's implement a similar system in our application, using middleware to determine user location:

// proxy.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';

// Table of regions and their available destinations
const REGION_DESTINATIONS = {
  'EU': ['mars', 'europa', 'titan'],
  'NA': ['mars', 'luna', 'titan', 'ganymede'],
  'ASIA': ['mars', 'venus-orbiter', 'luna'],
  'default': ['mars'] // default destinations available globally
};

export function proxy(request: NextRequest) {
  // Get user's region (in reality, you could use an external geolocation API)
  const countryCode = request.headers.get('x-country') || 'default';
  const region = getRegionFromCountry(countryCode);

  // Create response
  const response = NextResponse.next();

  // Add region info and available destinations as headers
  response.headers.set('x-user-region', region);
  response.headers.set('x-available-destinations', JSON.stringify(REGION_DESTINATIONS[region] || REGION_DESTINATIONS.default));

  // Set region cookie (will be available in the browser)
  response.cookies.set('user-region', region, {
    maxAge: 60 * 60 * 24 * 30, // 30 dni
    path: '/',
  });

  return response;
}

// Function mapping country codes to regions
function getRegionFromCountry(countryCode: string): keyof typeof REGION_DESTINATIONS {
  const EU_COUNTRIES = ['DE', 'FR', 'IT', 'ES', 'PL', 'NL', 'BE', 'SE', 'AT', 'DK'];
  const NA_COUNTRIES = ['US', 'CA', 'MX'];
  const ASIA_COUNTRIES = ['JP', 'CN', 'KR', 'IN', 'SG', 'TH', 'MY', 'PH', 'VN'];

  if (EU_COUNTRIES.includes(countryCode)) return 'EU';
  if (NA_COUNTRIES.includes(countryCode)) return 'NA';
  if (ASIA_COUNTRIES.includes(countryCode)) return 'ASIA';

  return 'default';
}

export const config = {
  matcher: '/((?!_next/static|_next/image|favicon.ico).*)',
};

Request Rate Limiting

In the Quantum Metropolis, the Gateway system controls the number of requests to critical resources to prevent overload. Let's implement a similar rate limiting mechanism:

// proxy.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';

// Simple memory-based rate limiting system (in production, better to use Redis or a similar service)
const RATE_LIMIT_DURATION = 60 * 1000; // 1 minute
const MAX_REQUESTS_PER_MINUTE = 60; // Maximum number of requests per minute

// Storing request counters for different IPs (in a real application, better to use Redis)
const ipRequestCounts = new Map<string, { count: number, resetAt: number }>();

export function proxy(request: NextRequest) {
  // We only limit API requests
  if (request.nextUrl.pathname.startsWith('/api/')) {
    // NextRequest no longer has an ip field (removed in Next.js 15) - the x-forwarded-for header carries the client address
    const ip = request.headers.get('x-forwarded-for')?.split(',')[0]?.trim() || 'unknown';
    const now = Date.now();

    // Get or create a counter for this IP
    if (!ipRequestCounts.has(ip) || ipRequestCounts.get(ip)!.resetAt < now) {
      // Reset the counter if time has elapsed
      ipRequestCounts.set(ip, { count: 1, resetAt: now + RATE_LIMIT_DURATION });
    } else {
      // Increment counter
      const record = ipRequestCounts.get(ip)!;
      record.count++;

      // Check if the limit has been exceeded
      if (record.count > MAX_REQUESTS_PER_MINUTE) {
        // Calculate the time after which requests can be sent again
        const resetTime = Math.ceil((record.resetAt - now) / 1000);

        // Return a response with 429 Too Many Requests code
        return new NextResponse('Rate limit exceeded', {
          status: 429,
          headers: {
            'Retry-After': `${resetTime}`,
            'X-RateLimit-Limit': `${MAX_REQUESTS_PER_MINUTE}`,
            'X-RateLimit-Remaining': '0',
            'X-RateLimit-Reset': `${resetTime}`,
          },
        });
      }
    }
  }

  return NextResponse.next();
}

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

A/B Testing with Middleware

In the Quantum Metropolis, some new features are tested on selected groups of residents. Let's implement a similar A/B testing system:

// proxy.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';

// A/B test definitions
const AB_TESTS = {
  'new-landing-page': {
    variants: ['control', 'variant-a', 'variant-b'],
    weights: [0.5, 0.25, 0.25], // 50% of users will see control, 25% variant-a, 25% variant-b
  },
  'checkout-flow': {
    variants: ['standard', 'simplified'],
    weights: [0.5, 0.5], // 50% of users will see each variant
  },
};

export function proxy(request: NextRequest) {
  const response = NextResponse.next();

  // Assign the user to test groups
  Object.entries(AB_TESTS).forEach(([testName, test]) => {
    // Get existing variant from cookie or assign a new one
    let variant = request.cookies.get(`ab-${testName}`)?.value;

    if (!variant || !test.variants.includes(variant)) {
      // Assign variant based on weights
      variant = assignVariant(test.variants, test.weights);

      // Save the variant in a cookie
      response.cookies.set(`ab-${testName}`, variant, {
        maxAge: 60 * 60 * 24 * 30, // 30 dni
        path: '/',
      });
    }

    // Add variant info as a header for the client
    response.headers.set(`x-ab-${testName}`, variant);
  });

  return response;
}

// Function assigning a variant based on weights
function assignVariant(variants: string[], weights: number[]): string {
  const random = Math.random();
  let cumulativeWeight = 0;

  for (let i = 0; i < variants.length; i++) {
    cumulativeWeight += weights[i];
    if (random < cumulativeWeight) {
      return variants[i];
    }
  }

  // Default to the first variant
  return variants[0];
}

export const config = {
  matcher: '/((?!api|_next/static|_next/image|favicon.ico).*)',
};

Monitoring and Debugging Middleware

In production applications, it's important to monitor middleware behavior. We can implement a simple logging system:

// proxy.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';

export function proxy(request: NextRequest) {
  const startTime = Date.now();

  // Create a request identifier
  const requestId = generateRequestId();

  // Create response
  const response = NextResponse.next();

  // Add request identifier to headers
  response.headers.set('x-request-id', requestId);

  // Time spent in the proxy itself (the page renders only after it, so this is not the time of the whole request)
  const duration = Date.now() - startTime;
  response.headers.set('x-response-time', `${duration}ms`);

  // In production, you could send this data to a monitoring system
  // logRequest(requestId, request.method, request.url, response.status, duration);

  return response;
}

// Generating a unique request identifier
function generateRequestId(): string {
  return `${Date.now()}-${Math.random().toString(36).substring(2, 15)}`;
}

export const config = {
  matcher: '/((?!_next/static|_next/image|favicon.ico).*)',
};

Integration with External Systems

Middleware can also integrate with external systems, such as authentication or analytics systems:

// proxy.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';

export async function proxy(request: NextRequest) {
  // Get session info from an external service
  const sessionId = request.cookies.get('session-id')?.value;
  let userInfo = null;

  if (sessionId) {
    try {
      // In a real application, this could be an API call
      userInfo = await fetchUserInfo(sessionId);
    } catch (error) {
      console.error('Error fetching user info:', error);
    }
  }

  // Create response
  const response = NextResponse.next();

  // If we have user info, add it to headers
  if (userInfo) {
    response.headers.set('x-user-id', userInfo.id);
    response.headers.set('x-user-plan', userInfo.plan);

    // Send data to the analytics system
    trackUserActivity(userInfo.id, request.url, request.method);
  }

  return response;
}

// Function fetching user info (simulation)
async function fetchUserInfo(sessionId: string) {
  // In a real application, this could be an API call
  return new Promise(resolve => {
    setTimeout(() => {
      resolve({
        id: 'user-123',
        plan: 'premium',
        name: 'John Doe'
      });
    }, 50);
  });
}

// Function tracking user activity (simulation)
function trackUserActivity(userId: string, url: string, method: string) {
  // In a real application, this could send data to Google Analytics, Mixpanel, etc.
  console.log(`User ${userId} accessed ${url} with method ${method}`);
}

export const config = {
  matcher: '/((?!_next/static|_next/image|favicon.ico).*)',
};

Summary

Proxy in Next.js 16 (formerly Middleware) is a powerful tool that, like the Quantum Gateway in the Quantum Metropolis, enables controlling and modifying traffic in the application at the very beginning of the request-response cycle. Thanks to this, we can:

  1. Implement advanced authorization systems - verify JWT tokens, redirect unauthenticated users, control access to protected resources.

  2. Add internationalization features - detect the user's preferred language, redirect to appropriate language versions.

  3. Personalize user experience - adjust content based on location, preferences, and user history.

  4. Optimize performance - control caching headers, modify responses, implement rate limiting.

  5. Integrate with external systems - connect with analytics, authentication, and other services.

  6. Conduct A/B tests - assign users to test groups and personalize the experience.

  7. Monitor and debug - track requests, measure performance, record metrics.

By leveraging middleware, we can significantly extend the capabilities of our Next.js 16 application, adding advanced features that are executed early in the request lifecycle, allowing for greater control and better performance.

In the next lesson you will learn prefetching and other ways to speed up navigation in Next.js 16.

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. Metadata in App Router is defined by:

  2. 2. Private Folders in App Router are marked with the prefix:

  3. 3. By default, components in App Router without the 'use client' directive:

  4. 4. To create a Client Component, you need to add:

  5. 5. What is prefetching in Next.js?

  6. 6. In Next.js 16, what must the file in the project root that replaced middleware.ts and runs before a request is handled be called?

  7. 7. How does router.replace() differ from router.push() from the useRouter hook?

  8. 8. What prefix must an environment variable have to be accessible on the client side in Next.js?

  9. 9. Parallel Routes in App Router use the naming convention:

  10. 10. What happens when you call the notFound() function inside a Server Component in Next.js 16?

  11. 11. Why must the error.tsx file in Next.js 16 be a Client Component (with the 'use client' directive)?

  12. 12. What is the template.tsx file best suited for instead of layout.tsx?

Hands-on tasks in the game

  • Code editor

    Create the catch-all route app/docs/[...slug]/page.js: default-export an async DocsPage({ params }) component, read the array of segments with const { slug } = await params and display each URL segment in its own li element of a ul list.

  • Vertical ordering

    Arrange the order of handling an error with the error.js file

  • Click in order

    Arrange the correct file path for a catch-all route in Next.js

  • Vertical ordering

    Arrange the syntax of the root layout (app/layout.tsx) in App Router

  • Vertical ordering

    Arrange the static page generation order in App Router

  • Vertical ordering

    Arrange the root layout syntax with html and body tags

  • Click in order

    Arrange the correct path to a dynamic product page in App Router

  • Vertical ordering

    Arrange the Incremental Static Regeneration process order

  • Click in order

    Arrange the usePathname syntax in a component

  • Vertical ordering

    Arrange the steps of navigating with the Link component: from the link appearing on screen to the page update

  • Vertical ordering

    Arrange the metadata resolution order in Next.js

  • Vertical ordering

    Arrange the import and usage syntax of the useRouter hook

  • Click in order

    Arrange the generateMetadata syntax

  • Vertical ordering

    Arrange the steps of optimizing a font with next/font (from the build to displaying text)

  • Vertical ordering

    Arrange the usage syntax of the Script component from Next.js

  • Vertical ordering

    Arrange the Server Components rendering order

  1. QuestionMetadata in App Router
  2. QuestionPrivate Folders in App Router
  3. Coding taskPractice: Catch-All Route
  4. Put in orderError Handling in error.js
  5. Click in orderCatch-All Route Syntax
  6. Put in orderlayout.tsx Structure
  7. QuestionDefault Rendering in App Router
  8. QuestionCreating a Client Component
  9. Put in orderStatic Page Generation
  10. Put in orderRoot Layout with html and body
  11. QuestionPrefetching in Next.js
  12. Click in orderDynamic Product Route Path
  13. Put in orderISR Process
  14. QuestionFile That Runs Before a Request Is Handled
  15. Click in orderusePathname Syntax in a Component
  16. Questionrouter.push vs router.replace
  17. Put in orderNavigating with the Link Component
  18. QuestionPublic Environment Variables in Next.js
  19. QuestionParallel Routes Convention
  20. Put in orderMetadata Resolution
  21. Put in orderImporting and Using useRouter
  22. Click in ordergenerateMetadata Syntax
  23. Put in orderFont Optimization Pipeline
  24. Put in orderUsing the Script Component
  25. Put in orderServer Components Rendering Cycle
  26. QuestionThe not-found.tsx Component in Next.js
  27. QuestionError Boundary with error.tsx
  28. QuestionWhen to Use template.tsx

Useful articles