Route Handlers

Learn how to create and manage route handlers in your application.

Overview

Route handlers are functions that process incoming requests and return responses. They are the core building blocks of your application's API.

Basic Route Handler

Start with a minimal handler and return a clear response. Keep handlers small and delegate business logic to utilities when needed.

export async function GET(request: Request) {
  return new Response('Hello, World!');
}

Handler Types

Most applications need at least GET and POST. Add other methods only when the workflow requires them.

Handles GET requests to retrieve data:

export async function GET(request: Request) {
  const data = await fetchData()
  return Response.json(data)
}

Request Processing

  1. 1

    Parse Request

    Extract data from the request:

    const body = await request.json();
    const searchParams = request.nextUrl.searchParams;
  2. 2

    Process Data

    Perform necessary operations with the data.

  3. 3

    Return Response

    Send back appropriate response:

    return Response.json({ success: true });

Error Handling

Always assume inputs can be malformed and dependencies can fail. Return consistent JSON errors and keep status codes meaningful.

note

Always implement proper error handling in your route handlers to ensure robust API endpoints.

try {
  // Process request
} catch (error) {
  return Response.json({ error: error.message }, { status: 500 });
}

Next Steps

Once your route handlers are stable, add middleware for cross-cutting concerns like authentication and logging.