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.
Route handlers (route.ts) in 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.
import { NextRequest, NextResponse } from 'next/server'; export async function GET(request: NextRequest) { return NextResponse.json({ message: 'Hello GET' }); }
import { NextRequest, NextResponse } from 'next/server'; export async function POST(request: NextRequest) { const data = await request.json(); return NextResponse.json({ received: data }); }
import { NextRequest, NextResponse } from 'next/server'; export async function DELETE(request: NextRequest) { return NextResponse.json({ message: 'Deleted' }); }
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.
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 }); }
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.
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.
Practice
route.ts file in Next.js?Solution
Step 1: Understand the role of
Theroute.tsroute.tsfile is used in Next.js to write server-side code that responds to HTTP requests for a specific route.Step 2: Compare with other options
Styling, client components, and database configs are handled elsewhere, not inroute.ts.Final Answer:
To define server-side code that handles HTTP requests for a specific URL -> Option DQuick Check:
Route handlers = server code for URLs [OK]
- Confusing route.ts with client component files
- Thinking route.ts is for styling
- Assuming route.ts manages database directly
route.ts?Solution
Step 1: Recall Next.js route handler syntax
Next.js expects exported async functions named exactly by HTTP method in uppercase, e.g.,GET, withNextRequestparameter and returningNextResponse.Step 2: Check each option
export async function GET(request: NextRequest) { return NextResponse.json({ message: 'Hi' }) } matches correct syntax: async, uppercase GET, parameter, and returns NextResponse. Others have wrong function names, casing, or return types.Final Answer:
export async function GET(request: NextRequest) { return NextResponse.json({ message: 'Hi' }) } -> Option AQuick Check:
Uppercase method + NextRequest + NextResponse = correct [OK]
- Using lowercase method names like get instead of GET
- Missing NextRequest parameter
- Returning plain string instead of NextResponse
route.ts code, what will be the JSON response body when a GET request is made?
import { NextResponse } from 'next/server';
export async function GET() {
return NextResponse.json({ success: true, data: [1, 2, 3] });
}Solution
Step 1: Analyze the GET handler return
The GET function returnsNextResponse.jsonwith an object containingsuccess: trueanddata: [1, 2, 3].Step 2: Understand JSON response format
This creates a JSON response with the exact object serialized as a JSON string.Final Answer:
{"success":true,"data":[1,2,3]} -> Option BQuick Check:
NextResponse.json outputs JSON string [OK]
- Expecting just the array without wrapping object
- Confusing error responses with success
- Thinking response is undefined
route.ts code snippet:
export async function POST(request: NextRequest) {
const data = await request.json();
return new Response(JSON.stringify(data));
}
export async function GET() {
return new Response('Hello');
}Solution
Step 1: Check imports
The code usesNextRequestbut does not import it from 'next/server'. This causes a runtime error.Step 2: Validate other parts
GET handler can omit request parameter if unused. ReturningResponseis allowed but NextResponse is preferred; not an error. So main error is missing import.Final Answer:
Missing import of NextRequest -> Option AQuick Check:
Using NextRequest requires import [OK]
- Forgetting to import NextRequest
- Thinking GET must have request param
- Confusing Response and NextResponse as errors
route.ts that responds to both GET and POST requests. The GET returns a JSON list of users, and the POST adds a user from the request body and returns the updated list. Which code snippet correctly implements this behavior?Solution
Step 1: Check imports and state management
import { NextRequest, NextResponse } from 'next/server'; let users = ['Alice', 'Bob']; export async function GET() { return NextResponse.json(users); } export async function POST(request: NextRequest) { const newUser = await request.json(); users.push(newUser.name); return NextResponse.json(users); } correctly imports NextRequest and NextResponse, and uses a mutable users array to store state between calls.Step 2: Verify GET and POST handlers
GET returns current users as JSON. POST reads JSON body, adds new user, then returns updated list. This matches requirements.Step 3: Review other options
import { NextRequest } from 'next/server'; const users = []; export function get() { return users; } export function post(request) { users.push(request.body.name); return users; } uses lowercase method names and no NextResponse, invalid in Next.js route handlers. export async function GET(request) { return new Response(JSON.stringify(['Alice', 'Bob'])); } export async function POST(request) { const data = await request.json(); return new Response(JSON.stringify(['Alice', 'Bob'])); } returns new Response but does not maintain state. import { NextResponse } from 'next/server'; export async function GET() { return NextResponse.json(['Alice', 'Bob']); } export async function POST() { return NextResponse.json(['Alice', 'Bob', 'Charlie']); } POST does not accept request or update users dynamically.Final Answer:
import { NextRequest, NextResponse } from 'next/server'; let users = ['Alice', 'Bob']; export async function GET() { return NextResponse.json(users); } export async function POST(request: NextRequest) { const newUser = await request.json(); users.push(newUser.name); return NextResponse.json(users); } -> Option CQuick Check:
Correct imports + state + async handlers = import { NextRequest, NextResponse } from 'next/server'; let users = ['Alice', 'Bob']; export async function GET() { return NextResponse.json(users); } export async function POST(request: NextRequest) { const newUser = await request.json(); users.push(newUser.name); return NextResponse.json(users); } [OK]
- Using lowercase method names instead of uppercase
- Not importing NextRequest or NextResponse
- Not maintaining state between requests
- Ignoring async/await for request.json()
Ready to prove it?
Pass the test and this pattern moves unknown
