Bird
Raised Fist0
Svelteframework~10 mins

GET, POST, PUT, DELETE handlers in Svelte - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - GET, POST, PUT, DELETE handlers
Client sends HTTP request
↓
Server receives request
↓
Check HTTP method
↓
Fetch
↓
Send response back to client
The server listens for HTTP requests, checks the method (GET, POST, PUT, DELETE), then runs the matching handler to fetch, create, update, or delete data, and finally sends a response.
Execution Sample
Svelte
import { json } from '@sveltejs/kit';

export async function GET() {
  return json({ message: 'Hello GET' });
}

export async function POST({ request }) {
  const data = await request.json();
  return json({ received: data });
}
This SvelteKit code defines GET and POST handlers that respond with JSON data.
Execution Table
StepHTTP MethodRequest DataHandler ActionResponse Sent
1GETNoneReturn JSON { message: 'Hello GET' }{ message: 'Hello GET' }
2POST{ name: 'Alice' }Parse JSON, return { received: { name: 'Alice' } }{ received: { name: 'Alice' } }
3PUT{ id: 1, name: 'Bob' }Update resource with id 1, return confirmation{ updated: { id: 1, name: 'Bob' } }
4DELETE{ id: 1 }Delete resource with id 1, return confirmation{ deleted: 1 }
5PATCHAnyNo handler defined, return 405 Method Not Allowed405 Method Not Allowed
💡 Execution stops after sending response for each request.
Variable Tracker
VariableStartAfter GETAfter POSTAfter PUTAfter DELETEFinal
requestDataundefinedundefined{ name: 'Alice' }{ id: 1, name: 'Bob' }{ id: 1 }undefined
responseDataundefined{ message: 'Hello GET' }{ received: { name: 'Alice' } }{ updated: { id: 1, name: 'Bob' } }{ deleted: 1 }undefined
Key Moments - 3 Insights
Why does the POST handler read request.json() but the GET handler does not?
Because POST requests usually send data in the body, so we parse it with request.json(). GET requests do not have a body, so no parsing is needed. See execution_table rows 1 and 2.
What happens if a request uses an HTTP method without a handler?
The server returns a 405 Method Not Allowed response, as shown in execution_table row 5.
How does the server know which handler to run?
It checks the HTTP method of the incoming request and runs the matching handler function (GET, POST, PUT, DELETE). See concept_flow diagram.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what response is sent for the POST request?
A{ message: 'Hello GET' }
B{ received: { name: 'Alice' } }
C{ updated: { id: 1, name: 'Bob' } }
D405 Method Not Allowed
💡 Hint
Check execution_table row 2 under Response Sent column.
At which step does the server respond with a 405 error?
AStep 1
BStep 3
CStep 5
DStep 4
💡 Hint
Look for the row with '405 Method Not Allowed' in the Response Sent column.
If the PUT handler was missing, what would happen at step 3?
AReturn 405 Method Not Allowed
BReturn the GET response
CReturn empty response
DServer crashes
💡 Hint
Refer to key_moments about missing handlers and execution_table step 5.
Concept Snapshot
GET, POST, PUT, DELETE handlers in SvelteKit:
- Export async functions named GET, POST, PUT, DELETE
- GET reads no body, returns data
- POST/PUT read request.json() to get data
- DELETE usually uses params or body to identify resource
- If method missing, server returns 405 error
- Handlers return JSON responses with json() helper
Full Transcript
In SvelteKit, you create server route files that export async functions named after HTTP methods: GET, POST, PUT, DELETE. When a client sends a request, the server checks the method and runs the matching function. GET handlers usually return data without reading a body. POST and PUT handlers read JSON data from the request body using request.json(). DELETE handlers remove resources identified by parameters or body data. If a request uses a method without a handler, the server responds with a 405 Method Not Allowed error. Each handler returns a JSON response using the json() helper from '@sveltejs/kit'. This flow ensures the server handles different HTTP methods properly and sends back the right responses.

Practice

(1/5)
1. In SvelteKit, what is the main purpose of a GET handler in a route's +server.js file?
easy
A. To update existing data on the server
B. To delete data from the server
C. To fetch and return data when the route is requested
D. To send data to the server without expecting a response

Solution

  1. Step 1: Understand the role of HTTP methods

    GET requests are used to retrieve data from a server without changing it.
  2. Step 2: Apply this to SvelteKit handlers

    The GET handler in +server.js responds to GET requests by returning data to the client.
  3. Final Answer:

    To fetch and return data when the route is requested -> Option C
  4. Quick Check:

    GET handler fetches data = B [OK]
Hint: GET handlers always return data for reading [OK]
Common Mistakes:
  • Confusing GET with POST or PUT for data updates
  • Thinking GET modifies server data
  • Assuming GET sends data without response
2. Which of the following is the correct syntax to define a POST handler in SvelteKit's +server.js file?
easy
A. export async function POST({ request }) { return new Response('ok'); }
B. export async function post(request) { return new Response('ok'); }
C. export function Post(request) { return 'ok'; }
D. async function POST() { return 'ok'; }

Solution

  1. Step 1: Recall SvelteKit handler naming conventions

    Handlers must be exported async functions named in uppercase: GET, POST, PUT, DELETE.
  2. Step 2: Check parameter and return type

    The function receives an object with a request property and returns a Response object.
  3. Final Answer:

    export async function POST({ request }) { return new Response('ok'); } -> Option A
  4. Quick Check:

    Correct handler syntax = A [OK]
Hint: Use uppercase method names and destructured params [OK]
Common Mistakes:
  • Using lowercase function names like 'post'
  • Not exporting the function
  • Returning plain strings instead of Response objects
3. Given this SvelteKit PUT handler in +server.js:
export async function PUT({ request }) {
  const data = await request.json();
  return new Response(JSON.stringify({ updated: data.id }), { status: 200 });
}

What will be the response body if the client sends {"id": 42} in the request body?
medium
A. undefined
B. {"id":42}
C. 42
D. {"updated":42}

Solution

  1. Step 1: Parse JSON from request

    The handler reads JSON from the request body, so data = { id: 42 }.
  2. Step 2: Return JSON with updated id

    The response body is JSON stringified object with key 'updated' and value data.id (42).
  3. Final Answer:

    {"updated":42} -> Option D
  4. Quick Check:

    Response JSON includes updated id = D [OK]
Hint: PUT returns updated data wrapped in JSON [OK]
Common Mistakes:
  • Returning original data instead of updated key
  • Not stringifying JSON response
  • Confusing response body with request body
4. Identify the error in this DELETE handler code snippet:
export async function DELETE(request) {
  const id = await request.json().id;
  return new Response(`Deleted ${id}`, { status: 200 });
}
medium
A. The function parameter should be destructured to get request
B. Cannot await request.json().id directly; must await request.json() first
C. DELETE handlers cannot return Response objects
D. Missing export keyword before function

Solution

  1. Step 1: Analyze request.json() usage

    request.json() returns a Promise for the parsed body; you must await it fully before accessing properties.
  2. Step 2: Identify incorrect await usage

    Code tries to await request.json().id directly, which is invalid; must await request.json() first, then access .id.
  3. Final Answer:

    Cannot await request.json().id directly; must await request.json() first -> Option B
  4. Quick Check:

    Await full JSON before property access = C [OK]
Hint: Await request.json() fully before accessing properties [OK]
Common Mistakes:
  • Trying to await a property of a Promise
  • Not destructuring the parameter (optional but recommended)
  • Thinking DELETE handlers can't return Response
5. You want to create a SvelteKit API route that updates a user's name using a PUT handler and returns the updated user object. Which code snippet correctly implements this behavior?
hard
A. export async function PUT({ request }) { const user = await request.json(); user.name = user.name.toUpperCase(); return new Response(JSON.stringify(user), { status: 200 }); }
B. export async function PUT(request) { const user = await request.json(); user.name = user.name.toUpperCase(); return user; }
C. export async function put({ request }) { const user = await request.json(); user.name = user.name.toUpperCase(); return new Response(JSON.stringify(user)); }
D. export async function PUT({ request }) { const user = request.json(); user.name = user.name.toUpperCase(); return new Response(JSON.stringify(user), { status: 200 }); }

Solution

  1. Step 1: Confirm correct function signature and export

    The handler must be exported async function named PUT with destructured { request } parameter.
  2. Step 2: Await request.json() and modify data

    Await the JSON body, then update the user.name property correctly.
  3. Step 3: Return a Response with JSON string and status

    Return new Response with JSON stringified user and status 200.
  4. Final Answer:

    export async function PUT({ request }) { const user = await request.json(); user.name = user.name.toUpperCase(); return new Response(JSON.stringify(user), { status: 200 }); } -> Option A
  5. Quick Check:

    Proper async PUT handler with Response = A [OK]
Hint: Use uppercase function name, await JSON, return Response [OK]
Common Mistakes:
  • Not awaiting request.json()
  • Using lowercase function name 'put'
  • Returning raw object instead of Response
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard