Performance: Response helpers (json, error)
This affects how quickly the server sends responses and how efficiently the browser processes them, impacting page load and interaction speed.
import { json } from '@sveltejs/kit'; export async function GET() { return json({ message: 'Hello' }); }
export async function GET() { const data = { message: 'Hello' }; return new Response(JSON.stringify(data), { headers: { 'Content-Type': 'application/json' } }); }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Manual JSON.stringify and Response | N/A | 0 | Minimal | [!] OK |
| Using json() helper from SvelteKit | N/A | 0 | Minimal | [OK] Good |
| Manual error Response with plain text | N/A | Possible extra client reflows if UI shifts | Medium if layout shifts | [X] Bad |
| Using error() helper from SvelteKit | N/A | 0 | Minimal | [OK] Good |
json() helper in SvelteKit server endpoints?json()json() helper formats data as a JSON response for the client.error(), which throws HTTP errors, json() sends data successfully.json() sends JSON data [OK]json() helper takes data as first argument and an options object with status as second.{ status: 200 } as the second argument.import { json, error } from '@sveltejs/kit';
export function GET() {
const data = { user: 'Alice' };
if (!data.user) {
throw error(404, 'User not found');
}
return json(data);
}data.user is missing?data.user is missing (falsy), the code throws error(404, 'User not found').error() helper throws an HTTP error with the given status and message.import { json, error } from '@sveltejs/kit';
export function POST() {
const data = { success: true };
return error(200, 'All good');
}error() helper requires status codes 400-599. Using 200 triggers "Non-error status code 200".json() instead of error().error(400, 'No items found') when the list is empty.json(items) properly when items exist.Pass the test and this pattern moves unknown