
- Next.js - Home
- Next.js - Overview
- Next.js - Project Setup
- Next.js - Folder Structure
- Next.js - App Router
- Next.js - Page Router
- Next.js Features
- Next.js - Pages
- Next.js - Data Fetching
- Next.js - ISR
- Next.js - Static File Serving
- Next.js - Pre-Rendering
- Next.js - Partial Pre Rendering
- Next.js - Server Side Rendering
- Next.js - Client Side Rendering
- Next.js Routing
- Next.js - Routing
- Next.js - Nested Routing
- Next.js - Dynamic Routing
- Next.js - Parallel Routing
- Next.js - Imperative Routing
- Next.js - Shallow Routing
- Next.js - Intercepting Routes
- Next.js - Redirecting Routes
- Next.js - Navigation and Linking
- Next.js Configuration
- Next.js - TypeScript
- Next.js - Environment Variables
- Next.js - File Conventions
- Next.js - ESLint
- Next.js API & Backend
- Next.js - API Routes
- Next.js - Dynamic API Routes
- Next.js - Route Handlers
- Next.js - API MiddleWares
- Next.js - Response Helpers
- Next.js API Reference
- Next.js - CLI Commands
- Next.js - Functions
- Next.js - Directives
- Next.js - Components
- Next.js - Image Component
- Next.js - Font Component
- Next.js - Head Component
- Next.js - Form Component
- Next.js - Link Component
- Next.js - Script Component
- Next.js Styling & SEO
- Next.js - CSS Support
- Next.js - Global CSS Support
- Next.js - Meta Data
- Next.js Advanced Topics
- Next.js - Error Handling
- Next.js - Server Actions
- Next.js - Fast Refresh
- Next.js - Internationalization
- Next.js - Authentication
- Next.js - Session Management
- Next.js - Authorization
- Next.js - Caching
- Next.js - Data Caching
- Next.js - Router Caching
- Next.js - Full Route Caching
- Next.js - Request Memoization
- Next.js Performance Optimization
- Next.js - Optimizations
- Next.js - Image Optimization
- Next.js - Lazy Loading
- Next.js - Font Optimization
- Next.js - Video Optimization
- Next.js - Script Optimization
- Next.js - Memory Optimization
- Next.js - Using OpenTelemetry
- Next.js - Package Bundling Optimization
- Next.js Testing
- Next.js - Testing
- Next.js - Testing with Jest
- Next.js - Testing with Cypress
- Next.js - Testing with Vitest
- Next.js - Testing with Playwright
- Next.js Debugging & Deployment
- Next.js - Debugging
- Next.js - Deployment
- Next.js Useful Resources
- Next.js - Interview Questions
- Next.js - Quick Guide
- Next.js - Useful Resources
- Next.js - Discussion
Next.js - Route Handlers
In this chapter, we will learn route handlers in Next.js, how to create route handlers and handle different HTTP methods in route handler.
Route Handlers in Next.js
Route Handlers in Next.js are used to create server-side API endpoints that can handle requests from the frontend or any external client. These handlers are defined using a file-based routing system and can be used to define server-side logic for fetching data, submitting forms, or implementing server-side operations.
How it Works?
- Route Handlers in Next.js are created by adding a 'route.js' or 'route.ts' file inside the app directory.
- Any route.js/ts file inside the app/api directory is treated as an API endpoint.
- Any next.js component can call this API using the specified endpoint.
- For example, if you create a route.js file at 'app/api/hello/route.js', the endpoint will be '/api/hello'.
Route Handlers can be nested anywhere inside the app directory, similar to page.js and layout.js. But there cannot be a route.js file at the same route segment level as page.js
Note: Route Handlers are specific to the App Router architecture in Next.js. If you're using the Pages Router, you should use API Routes instead.
Setting Up a Route Handler
Let's create a basic route handler that returns a JSON response. Create a file named 'route.js' inside the 'app/api/hello' directory with the following code:
// File: app/api/hello/route.js import { NextResponse } from 'next/server'; export async function GET() { return NextResponse.json({ message: 'Hello from Route Handler!' }); }
Output
Now, if you visit the URL '/api/hello', you will see the following JSON response:

Handling HTTP Methods
Route Handlers in Next.js can handle different HTTP methods by exporting functions named after the HTTP method they handle. Each function can process requests differently and return appropriate responses.
Example
In the following example, we create a route handler (app/api/users/route.ts) that handles different HTTP methods, and a React component (app/test-handler/page.tsx) that interacts with these endpoints.
// File: app/api/users/route.ts import { NextResponse } from 'next/server'; export async function GET() { return NextResponse.json( { message: 'Fetching users' }, { status: 200 } ); } export async function POST(request: Request) { const data = await request.json(); return NextResponse.json( { message: 'Creating user', data }, { status: 201 } ); } export async function PUT(request: Request) { const data = await request.json(); return NextResponse.json( { message: 'Updating user', data }, { status: 200 } ); } export async function DELETE(request: Request) { const { searchParams } = new URL(request.url); const id = searchParams.get('id'); return NextResponse.json( { message: 'Deleting user', id }, { status: 200 } ); } // File: app/test-handler/page.tsx 'use client'; import { useState } from 'react'; export default function TestHandler() { const [response, setResponse] = useState(null); const callHandler = async (method) => { try { const res = await fetch('/api/users', { method, headers: { 'Content-Type': 'application/json', }, ...(method === 'POST' || method === 'PUT' ? { body: JSON.stringify({ name: 'John Doe' }) } : {}), }); const data = await res.json(); setResponse(data); } catch (error) { setResponse({ error: error.message }); } }; return ( <div> <h1>Test Route Handlers</h1> <div> <button onClick={() => callHandler('GET')}>GET</button> <button onClick={() => callHandler('POST')}>POST</button> <button onClick={() => callHandler('PUT')}>PUT</button> <button onClick={() => callHandler('DELETE')}>DELETE</button> </div> <div> <h2>Response:</h2> <pre> {response ? JSON.stringify(response, null, 2) : 'No response yet'} </pre> </div> </div> ); }
Output
When you visit the URL '/test-handler', you will see a React component with buttons to interact with the route handlers. Clicking on each button will call the respective handler and display the response.
