Server routes let your app handle requests like getting or sending data. They work like helpers that listen and respond to users or other apps.
Server routes (+server.js) in Svelte
export async function GET() { // handle GET request return new Response('Hello from GET'); } export async function POST({ request }) { // handle POST request const data = await request.json(); return new Response(JSON.stringify({ message: 'Data received', data }), { headers: { 'Content-Type': 'application/json' } }); }
Each HTTP method (GET, POST, etc.) is a separate exported async function.
The handler receives an object with properties like request, params, url, and helpers.
export async function GET() { return new Response('Hello world'); }
export async function POST({ request }) { const data = await request.json(); return new Response(JSON.stringify({ received: data }), { headers: { 'Content-Type': 'application/json' } }); }
export async function DELETE() { return new Response('Deleted item'); }
This server route handles GET and POST requests at /api/message. GET returns a simple text message. POST reads JSON with a text property and replies with a JSON message.
// src/routes/api/message/+server.js export async function GET() { return new Response('Hello from server route!'); } export async function POST({ request }) { const data = await request.json(); const reply = `You sent: ${data.text}`; return new Response(JSON.stringify({ reply }), { headers: { 'Content-Type': 'application/json' } }); }
Server routes live in folders named with a +server.js file inside src/routes.
Use request (destructured from the handler function argument) to access request details like headers and body.
Always set proper Content-Type headers when returning JSON.
Server routes let your app respond to HTTP requests with code.
Each HTTP method is a separate exported async function in +server.js.
Use server routes to get, send, or process data securely on the server side.