tezvyn:

How do you create a POST API endpoint in SvelteKit?

AI-drafted, machine-checkedSource: svelte.devintermediate
How do you create a POST API endpoint in SvelteKit?
WHAT IT TESTS

Filesystem routing and server-only API routes in SvelteKit.

ANSWER OUTLINE

Add a +server.js file in a src/routes subdirectory, export a POST handler returning a Response, and note that +server files never run in the browser.

WHAT THIS TESTS: This question checks whether you know that SvelteKit uses a filesystem-based router where directories under src/routes map to URL paths, and whether you know that +server files are reserved for server-only logic that does not render pages. It also checks if you understand how to expose raw API endpoints using route files that are not page components.

A GOOD ANSWER COVERS: First, state that the endpoint path is created by adding a directory inside src/routes, such as src/routes/api/submit, because the router maps directories to URLs. Second, place a file named +server.js or +server.ts inside that directory, since route files are identified by the plus prefix and +server files run exclusively on the server. Third, explain that you export a function named POST to handle POST requests; this function receives the incoming request and should return a standard web Response object. Fourth, note that unlike +page.svelte or +page.js, a +server file does not render a component and never runs in the browser, making it the correct place for JSON APIs or form handling that must stay server-side.

COMMON WRONG ANSWERS: A major red flag is describing +page.server.js and its load function instead of +server.js, because load is for supplying data to pages, not for standalone API endpoints. Another mistake is suggesting the endpoint returns a Svelte component or uses SSR page rendering, since +server routes return raw responses. Candidates also err by claiming the code runs in the browser, but the documentation states that all files run on the client except +server files.

LIKELY FOLLOW-UPS: An interviewer might ask how you would read the request body inside the POST handler, how to return JSON with the correct content-type, or how to handle other verbs like GET in the same file. They might also ask about the difference between +server.js and +page.server.js, or how dynamic parameters like src/routes/api/item/id work in API routes.

ONE CONCRETE EXAMPLE: Suppose you need an endpoint at api/notify. You would create src/routes/api/notify/+server.js. Inside it you export an async function POST that accepts the request, reads the body, performs an action, and returns a new Response with JSON content and a 200 status. Because the file is named +server.js and lives in the notify directory, SvelteKit maps it to api/notify and restricts execution to the server only.

Read the original → svelte.dev

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.