Skip to content
Watch the complete Next.js 15 course on YouTube

Route handlers

This page explains how to implement custom request handlers using route handlers in Next.js.

Understanding route handlers

While page routes return HTML content, route handlers enable you to create RESTful endpoints with full control over the response. They function similarly to Express.js routes but are integrated directly into Next.js without requiring a separate server setup.

Route handlers support standard HTTP methods:

  • GET
  • POST
  • PUT
  • PATCH
  • DELETE
  • HEAD
  • OPTIONS

Attempting to use an unsupported method results in a 405 Method Not Allowed response.

Creating route handlers

To create a route handler:

  1. Create a route.ts file in your app directory
  2. Export functions named after HTTP methods
  3. Return a Response object
  • Directoryapp/
    • Directoryhello/
      • route.ts /hello
    • page.tsx /

Here’s a basic route handler:

app/hello/route.ts
export async function GET() {
return new Response("Hello world!");
}

Accessing /hello in the browser displays the text response.

Nested route handlers

Like page routes, you can organize route handlers in nested folders:

  • Directoryapp/
    • Directorydashboard/
      • route.ts /dashboard
      • Directoryusers/
        • route.ts /dashboard/users
app/dashboard/route.ts
export async function GET() {
return new Response("Dashboard data");
}
// app/dashboard/users/route.ts
export async function GET() {
return new Response("User data");
}

In the browser, accessing /dashboard displays the dashboard data, and /dashboard/users displays the user data.

Route conflicts

Route handlers and page routes at the same segment level create conflicts. For example:

app/profile/page.tsx
export default function ProfilePage() {
return <div>Profile Page</div>;
}
// app/profile/route.ts
export async function GET() {
return new Response("Profile API data");
}

In this case, the route handler takes precedence. One approach is to use the api directory to avoid route conflicts:

  1. Create an api directory within the route segment
  2. Move the route handler into the api directory
  • Directoryapp/
    • Directoryprofile/
      • Directoryapi/
        • route.ts /profile/api
      • page.tsx /profile

This separation allows both the page (/profile) and API endpoint (/profile/api) to coexist.

Common use cases

Route handlers are particularly useful for:

  • Building REST APIs
  • Handling form submissions
  • Managing database operations
  • Integrating with external services
  • Protecting sensitive API keys and credentials

Good to know

  • Route handlers must be placed in the app directory
  • They support all standard HTTP methods
  • Route handlers take precedence over page routes