Performance: HTTP method handlers (GET, POST)
This affects server response time and client perceived loading speed by how efficiently requests are handled and data is sent.
Jump into concepts and practice - no test required
import { cache } from 'react'; const fetchData = cache(async () => { const res = await fetch('https://api.example.com/data'); return res.json(); }); export async function GET(request) { const data = await fetchData(); return new Response(JSON.stringify(data)); } export async function POST(request) { const body = await request.json(); if (!body || !body.name) { return new Response('Invalid data', { status: 400 }); } await database.save(body); return new Response('Saved'); }
export async function GET(request) { const data = await fetch('https://api.example.com/data'); const json = await data.json(); return new Response(JSON.stringify(json)); } export async function POST(request) { const body = await request.json(); await database.save(body); return new Response('Saved'); }
| Pattern | Server Processing | Network Delay | Client Impact | Verdict |
|---|---|---|---|---|
| Blocking fetch and save without caching | High CPU and wait time | Longer due to slow response | Slower LCP and user wait | [X] Bad |
| Cached GET handler with input validation in POST | Lower CPU and faster response | Shorter due to caching | Faster LCP and better UX | [OK] Good |
GET or POST to handle those requests.GET will handle GET requests automatically.POST in uppercase to handle POST requests.export async function POST(request) {
const data = await request.json();
return new Response(JSON.stringify({ message: `Hello, ${data.name}!` }), { status: 200 });
}{"name": "Alice"} in the POST body.await request.json() to parse the JSON body sent by the client, which contains {"name": "Alice"}.data.name.export async function GET() {
return new Response('Hello GET');
}
export function POST(request) {
const data = request.json();
return new Response(`Hello ${data.name}`);
}request.json() which returns a promise, so it must be awaited and the function must be async.