Route Middleware

Learn how to implement and use middleware in your routes.

Overview

Middleware functions are pieces of code that run before your route handlers, allowing you to modify requests or responses, perform authentication, logging, or other operations.

Creating Middleware

  1. 1

    Define Middleware Function

    Create a middleware function:

    export function withLogging(handler) {
      return async function (request, ...args) {
        console.log(`${request.method} ${request.url}`);
        return handler(request, ...args);
      };
    }
  2. 2

    Apply Middleware

    Use the middleware in your route:

    export const GET = withLogging(async (request) => {
      return Response.json({ message: 'Hello' });
    });

Common Use Cases

Middleware is most useful when you want the same behavior applied across many routes without duplicating code.

Verify user authentication:

export function withAuth(handler) {
  return async function (request, ...args) {
    const token = request.headers.get('authorization')
    if (!token) {
      return Response.json(
        { error: 'Unauthorized' },
        { status: 401 }
      )
    }
    return handler(request, ...args)
  }
}

Best Practices

Keep middleware small, composable, and focused on a single responsibility.

Good to know

Keep middleware functions focused on a single responsibility and compose them together when needed.

Composing Middleware

Composition makes order explicit. Apply logging and error handling around auth so failures are visible and safe.

export const GET = withErrorHandling(
  withAuth(
    withLogging(async (request) => {
      // Your route handler code
    }),
  ),
);

Next Steps

After routing is in place, review data fetching patterns so handlers and pages stay consistent.