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.
Practice
+server.js file in a SvelteKit project?Solution
Step 1: Understand the role of
This file is used to write server-side code that responds to HTTP requests.+server.jsStep 2: Differentiate client and server roles
Client-side UI components and styling are handled elsewhere, not in+server.js.Final Answer:
To handle server-side HTTP requests like GET or POST -> Option DQuick Check:
Server routes = handle HTTP requests [OK]
+server.js is for server code only [OK]- Confusing
+server.jswith client components - Thinking CSS or styling goes in
+server.js - Assuming database code runs in the browser
+server.js file?Solution
Step 1: Recall SvelteKit server route syntax
Handlers must be exported as async functions named in uppercase HTTP methods, e.g.,GET.Step 2: Check syntax correctness
Only export async function GET() { return { body: { message: 'Hello' } }; } usesexport async function GET()which is correct syntax.Final Answer:
export async function GET() { return { body: { message: 'Hello' } }; } -> Option CQuick Check:
Use uppercase HTTP method names for exports [OK]
- Using lowercase method names like 'get' instead of 'GET'
- Omitting async keyword for async handlers
- Incorrect export syntax without 'function'
+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] }
};
}Solution
Step 1: Understand the returned object structure
The handler returns an object withstatusandbody. Thebodyis the JSON data sent to the client.Step 2: Identify the actual response body content
The client receives thebodycontent serialized as JSON: {"success":true,"data":[1,2,3]}.Final Answer:
{"success":true,"data":[1,2,3]} -> Option AQuick Check:
Response body = JSON data object [OK]
- Confusing the whole return object with the response body
- Expecting raw arrays or strings instead of JSON objects
- Thinking status code is part of JSON body
+server.js POST handler?
export async function POST(request) {
const data = await request.json();
return { status: 201, body: { received: data } };
}Solution
Step 1: Check handler parameter
The POST handler receives an event object containingrequest. The code names itrequestbut callsrequest.json(), which fails because the event object has nojson()method; useevent.request.json()or destructure{ request }.Step 2: Identify the correct fix
The parameter needs destructuring likePOST({ request })or renaming to event withevent.request. The request parameter is missing the 'event' wrapper correctly identifies the missing 'event' wrapper.Final Answer:
The request parameter is missing the 'event' wrapper -> Option BQuick Check:
Destructure { request } from event [OK]
- Using lowercase method names instead of uppercase
- Expecting a Response object instead of plain object
- Misunderstanding request parameter structure
+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?Solution
Step 1: Validate the 'name' field properly
The correct snippet destructures{ request }, checks ifnameexists, is a string, and non-empty aftertrim(), returning 400 if invalid.Step 2: Confirm status codes and completeness
It uses 400 for validation errors and 200 for success; others use wrong parameters, incomplete checks, wrong statuses (500/404), or throw errors.Final Answer:
The snippet with full validation (exists, string, trimmed non-empty) and 400 status -> Option AQuick Check:
Validate input and return 400 if invalid [OK]
- Returning wrong status codes like 404 or 500 for validation errors
- Throwing errors instead of returning HTTP responses
- Not trimming strings before checking emptiness
Ready to prove it?
Pass the test and this pattern moves unknown
