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:
- Create a
route.ts
file in your app directory - Export functions named after HTTP methods
- Return a Response object
Directoryapp/
Directoryhello/
- route.ts
/hello
- route.ts
- page.tsx
/
Here’s a basic route handler:
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
- route.ts
- route.ts
export async function GET() { return new Response("Dashboard data");}
// app/dashboard/users/route.tsexport 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:
export default function ProfilePage() { return <div>Profile Page</div>;}
// app/profile/route.tsexport 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:
- Create an
api
directory within the route segment - Move the route handler into the
api
directory
Directoryapp/
Directoryprofile/
Directoryapi/
- route.ts
/profile/api
- route.ts
- 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