0
0
NextJSframework~5 mins

Route handlers (route.ts) in NextJS

Choose your learning style9 modes available
Introduction

Route handlers let you create server-side code that responds to web requests in Next.js. They help you build APIs or handle form submissions easily.

You want to create an API endpoint to fetch or send data.
You need to handle form submissions on the server.
You want to respond differently to GET, POST, or other HTTP methods.
You want to keep server logic close to your Next.js app without a separate backend.
You want to build server-side logic that runs only when a specific URL is requested.
Syntax
NextJS
import { NextRequest, NextResponse } from 'next/server';

export async function GET(request: NextRequest) {
  // handle GET request
  return NextResponse.json({ message: 'Hello from GET' });
}

export async function POST(request: NextRequest) {
  // handle POST request
  const data = await request.json();
  return NextResponse.json({ received: data });
}

Each HTTP method (GET, POST, etc.) is a separate exported async function.

Use NextRequest to access request details and NextResponse to send responses.

Examples
Simple GET handler that returns a JSON message.
NextJS
import { NextRequest, NextResponse } from 'next/server';

export async function GET(request: NextRequest) {
  return NextResponse.json({ message: 'Hello GET' });
}
POST handler that reads JSON from the request and sends it back.
NextJS
import { NextRequest, NextResponse } from 'next/server';

export async function POST(request: NextRequest) {
  const data = await request.json();
  return NextResponse.json({ received: data });
}
DELETE handler example to respond to delete requests.
NextJS
import { NextRequest, NextResponse } from 'next/server';

export async function DELETE(request: NextRequest) {
  return NextResponse.json({ message: 'Deleted' });
}
Sample Program

This route handler file responds to GET requests with a greeting message. For POST requests, it reads JSON data sent by the client and returns it in the response.

NextJS
import { NextRequest, NextResponse } from 'next/server';

export async function GET(request: NextRequest) {
  return NextResponse.json({ greeting: 'Hello from GET route' });
}

export async function POST(request: NextRequest) {
  const data = await request.json();
  return NextResponse.json({ receivedData: data });
}
OutputSuccess
Important Notes

Route handler files must be named route.ts and placed inside the folder for the route.

Only export functions for HTTP methods you want to support.

Use await request.json() carefully; it only works if the request has JSON body.

Summary

Route handlers let you write server code for specific URLs in Next.js.

Each HTTP method is a separate exported async function.

Use NextRequest and NextResponse to work with requests and responses.