Performance: Server routes (+server.js)
This affects the server response time and initial page load speed by controlling how requests are handled and data is fetched before rendering.
import { cache } from '$lib/cache'; export async function GET() { if (cache.has('data')) { return new Response(JSON.stringify(cache.get('data'))); } const data = await fetch('https://external-api.com/data'); const json = await data.json(); cache.set('data', json); return new Response(JSON.stringify(json)); }
export async function GET() { const data = await fetch('https://external-api.com/data'); const json = await data.json(); return new Response(JSON.stringify(json)); }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| No caching in server routes | N/A (server-side) | N/A | N/A | [X] Bad |
| Caching data in server routes | N/A (server-side) | N/A | N/A | [OK] Good |
+server.js file in a SvelteKit project?+server.js+server.js.+server.js is for server code only [OK]+server.js with client components+server.js+server.js file?GET.export async function GET() which is correct syntax.+server.js code, what will be the JSON response body when a GET request is made?
export async function GET() {
return {
status: 200,
body: { success: true, data: [1, 2, 3] }
};
}status and body. The body is the JSON data sent to the client.body content serialized as JSON: {"success":true,"data":[1,2,3]}.+server.js POST handler?
export async function POST(request) {
const data = await request.json();
return { status: 201, body: { received: data } };
}request. The code names it request but calls request.json(), which fails because the event object has no json() method; use event.request.json() or destructure { request }.POST({ request }) or renaming to event with event.request. The request parameter is missing the 'event' wrapper correctly identifies the missing 'event' wrapper.+server.js route that accepts a POST request with JSON data, validates that the JSON has a non-empty name string, and returns a 400 error if invalid. Which code snippet correctly implements this?{ request }, checks if name exists, is a string, and non-empty after trim(), returning 400 if invalid.Pass the test and this pattern moves unknown