How does SvelteKit handle API routes?
Answer
SvelteKit API routes are created by adding +server.js files in the routes directory. Export named functions corresponding to HTTP methods: export async function GET({ params, url }) { const data = await db.query(params.id); return new Response(JSON.stringify(data), { headers: { 'Content-Type': 'application/json' } }); }. Alternatively, use the built-in json() helper: import { json } from '@sveltejs/kit'; return json(data);. Handle POST: export async function POST({ request }) { const body = await request.json(); ... }. Error responses: import { error } from '@sveltejs/kit'; throw error(404, 'Not found');. API routes support GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS. They share the hooks infrastructure (authentication via event.locals). Unlike form actions (for form submissions), API routes are for programmatic API access from client-side JavaScript or external clients.
More Svelte / SvelteKit Questions
View all →- Intermediate What are Svelte custom stores and the store contract?
- Intermediate How does SSR (Server-Side Rendering) work in SvelteKit?
- Intermediate What are SvelteKit adapters?
- Intermediate What is the difference between prerendering, SSR, and CSR in SvelteKit?
- Intermediate How do you manage environment variables in SvelteKit?