Performance: Route handlers (route.ts)
This affects server response time and initial page load speed by controlling how requests are handled and data is fetched.
Jump into concepts and practice - no test required
export async function GET(request) { const data = await fetch('https://external-api.com/data', { next: { cache: 'force-cache' } }); const json = await data.json(); return new Response(JSON.stringify(json)); }
export async function GET(request) { const data = await fetch('https://external-api.com/data'); const json = await data.json(); return new Response(JSON.stringify(json)); }
| Pattern | Server Processing | Network Delay | Response Time | Verdict |
|---|---|---|---|---|
| No caching, external API fetch on every request | High CPU and wait time | High due to external call | Slow (200-500ms+) | [X] Bad |
| Cached data fetch in route handler | Low CPU, fast retrieval | Low network delay | Fast (<50ms on repeated calls) | [OK] Good |
route.ts file in Next.js?route.tsroute.ts file is used in Next.js to write server-side code that responds to HTTP requests for a specific route.route.ts.route.ts?GET, with NextRequest parameter and returning 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] });
}NextResponse.json with an object containing success: true and data: [1, 2, 3].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');
}NextRequest but does not import it from 'next/server'. This causes a runtime error.Response is allowed but NextResponse is preferred; not an error. So main error is missing import.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?