Performance: Why API routes serve backend logic
API routes affect server response time and client load speed by handling backend logic separately from frontend rendering.
Jump into concepts and practice - no test required
export async function GET() { // API route handles backend logic server-side const data = await fetchDataFromDB(); return new Response(JSON.stringify({ message: data }), { status: 200 }); } export default async function Page() { // Fetch data server-side during rendering const res = await fetch('http://localhost:3000/api/data'); const data = await res.json(); return <div>{data.message}</div>; }
export default function Page() { // Fetch data directly inside the component using client-side fetch const [data, setData] = React.useState(null); React.useEffect(() => { fetch('/api/data').then(res => res.json()).then(setData); }, []); return <div>{data ? data.message : 'Loading...'}</div>; }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Client-side data fetching | Low | 1+ (due to delayed content) | High (delayed paint) | [X] Bad |
| Server-side API routes | Low | 1 (initial render) | Low (fast paint) | [OK] Good |
req and res to handle requests and responses.req and res and sends a JSON response. Others either lack export default or return JSX, which is incorrect for API routes.export default function handler(req, res) {
if (req.method === 'GET') {
res.status(200).json({ success: true, data: 'Hello World' })
} else {
res.status(405).json({ error: 'Method Not Allowed' })
}
}export default function handler(req, res) {
if (req.method === 'POST') {
res.json({ message: 'Data received' })
} else {
res.status(405).json({ error: 'Method Not Allowed' })
}
}res.json() sends a JSON response with a default status code of 200, which is correct and functional.res.json() (200 OK implied) and other methods with 405 error. There are no syntax errors, runtime issues, or missing parameters. res.json is the right method for JSON responses.