Bird
Raised Fist0
Svelteframework~20 mins

Server routes (+server.js) in Svelte - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Server Routes Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
1:30remaining
What does this +server.js GET route return?
Consider this SvelteKit +server.js file with a GET handler. What is the JSON response when you fetch this route?
Svelte
export async function GET() {
  return new Response(JSON.stringify({ message: 'Hello from server' }), {
    headers: { 'Content-Type': 'application/json' }
  });
}
A{"error":"Not found"}
Bundefined
C"Hello from server"
D{"message":"Hello from server"}
Attempts:
2 left
💡 Hint
The GET function returns a Response with JSON string and content-type header.
📝 Syntax
intermediate
1:30remaining
Which +server.js POST handler syntax is correct?
You want to create a POST handler in +server.js that reads JSON from the request body. Which option is syntactically correct?
A
export async function POST(request) {
  const data = await request.json();
  return new Response(JSON.stringify(data));
}
B
export async function POST({ request }) {
  const data = await request.json();
  return new Response(JSON.stringify(data));
}
C
export async function POST(req) {
  const data = req.json();
  return new Response(JSON.stringify(data));
}
D
export async function POST({ req }) {
  const data = await req.json();
  return new Response(JSON.stringify(data));
}
Attempts:
2 left
💡 Hint
SvelteKit passes an object with a request property to the handler.
🔧 Debug
advanced
2:00remaining
Why does this +server.js GET handler cause a runtime error?
This GET handler throws an error when called. What is the cause?
Svelte
export async function GET() {
  return {
    body: { message: 'Hi' }
  };
}
AThe handler must return a Response object, not a plain object with body.
BThe body property must be a string, not an object.
CThe function must be named get, not GET.
DThe handler must be synchronous, not async.
Attempts:
2 left
💡 Hint
SvelteKit expects a Response or a special object shape from server route handlers.
❓ state_output
advanced
1:30remaining
What is the response body after this POST handler runs?
Given this +server.js POST handler, what JSON does the client receive?
Svelte
export async function POST({ request }) {
  const { name } = await request.json();
  return new Response(JSON.stringify({ greeting: `Hello, ${name}!` }), {
    headers: { 'Content-Type': 'application/json' }
  });
}
A{"name":"Alice"}
B{"greeting":"Hello, undefined!"}
C{"greeting":"Hello, Alice!"}
D{"error":"Missing name"}
Attempts:
2 left
💡 Hint
The handler reads 'name' from the JSON body and returns a greeting string.
🧠 Conceptual
expert
2:00remaining
Which statement about +server.js route handlers is TRUE?
Select the correct statement about how +server.js route handlers work in SvelteKit.
AHandlers must always return a Response object; returning plain objects causes errors.
BHandlers can return plain objects with a 'body' property and SvelteKit converts them automatically.
CHandlers can only handle GET and POST methods; other HTTP methods are not supported.
DHandlers run only on the client side and cannot access server resources.
Attempts:
2 left
💡 Hint
Think about the expected return type of server route handlers.

Practice

(1/5)
1. What is the main purpose of a +server.js file in a SvelteKit project?
easy
A. To style the application using CSS
B. To define client-side UI components
C. To manage database connections directly in the browser
D. To handle server-side HTTP requests like GET or POST

Solution

  1. Step 1: Understand the role of +server.js

    This file is used to write server-side code that responds to HTTP requests.
  2. Step 2: Differentiate client and server roles

    Client-side UI components and styling are handled elsewhere, not in +server.js.
  3. Final Answer:

    To handle server-side HTTP requests like GET or POST -> Option D
  4. Quick Check:

    Server routes = handle HTTP requests [OK]
Hint: Remember: +server.js is for server code only [OK]
Common Mistakes:
  • Confusing +server.js with client components
  • Thinking CSS or styling goes in +server.js
  • Assuming database code runs in the browser
2. Which of the following is the correct way to export a GET handler in a +server.js file?
easy
A. export async function get() { return { body: { message: 'Hello' } }; }
B. export function get() { return { body: { message: 'Hello' } }; }
C. export async function GET() { return { body: { message: 'Hello' } }; }
D. export async get() { return { body: { message: 'Hello' } }; }

Solution

  1. Step 1: Recall SvelteKit server route syntax

    Handlers must be exported as async functions named in uppercase HTTP methods, e.g., GET.
  2. Step 2: Check syntax correctness

    Only export async function GET() { return { body: { message: 'Hello' } }; } uses export async function GET() which is correct syntax.
  3. Final Answer:

    export async function GET() { return { body: { message: 'Hello' } }; } -> Option C
  4. Quick Check:

    Use uppercase HTTP method names for exports [OK]
Hint: Export async functions named uppercase HTTP methods [OK]
Common Mistakes:
  • Using lowercase method names like 'get' instead of 'GET'
  • Omitting async keyword for async handlers
  • Incorrect export syntax without 'function'
3. Given this +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] }
  };
}
medium
A. {"success":true,"data":[1,2,3]}
B. {"status":200,"body":{"success":true,"data":[1,2,3]}}
C. [1, 2, 3]
D. An error because body must be a string

Solution

  1. Step 1: Understand the returned object structure

    The handler returns an object with status and body. The body is the JSON data sent to the client.
  2. Step 2: Identify the actual response body content

    The client receives the body content serialized as JSON: {"success":true,"data":[1,2,3]}.
  3. Final Answer:

    {"success":true,"data":[1,2,3]} -> Option A
  4. Quick Check:

    Response body = JSON data object [OK]
Hint: Response body is the JSON object inside returned body [OK]
Common Mistakes:
  • 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
4. What is wrong with this +server.js POST handler?
export async function POST(request) {
  const data = await request.json();
  return { status: 201, body: { received: data } };
}
medium
A. Nothing is wrong; this is correct syntax
B. The request parameter is missing the 'event' wrapper
C. The handler must return a Response object, not a plain object
D. The function should be named post in lowercase

Solution

  1. Step 1: Check handler parameter

    The POST handler receives an event object containing request. The code names it request but calls request.json(), which fails because the event object has no json() method; use event.request.json() or destructure { request }.
  2. Step 2: Identify the correct fix

    The parameter needs destructuring like POST({ request }) or renaming to event with event.request. The request parameter is missing the 'event' wrapper correctly identifies the missing 'event' wrapper.
  3. Final Answer:

    The request parameter is missing the 'event' wrapper -> Option B
  4. Quick Check:

    Destructure { request } from event [OK]
Hint: Destructure { request } from event parameter [OK]
Common Mistakes:
  • Using lowercase method names instead of uppercase
  • Expecting a Response object instead of plain object
  • Misunderstanding request parameter structure
5. You want to create a +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?
hard
A. export async function POST({ request }) { const data = await request.json(); if (!data.name || typeof data.name !== 'string' || data.name.trim() === '') { return { status: 400, body: { error: 'Name is required' } }; } return { status: 200, body: { message: `Hello, ${data.name}` } }; }
B. export async function POST(request) { const data = await request.json(); if (!data.name) { throw new Error('Name missing'); } return new Response(JSON.stringify({ message: `Hello, ${data.name}` }), { status: 200 }); }
C. export async function POST({ request }) { const data = await request.json(); if (data.name === '') { return { status: 500, body: { error: 'Empty name' } }; } return { status: 200, body: { message: `Hi ${data.name}` } }; }
D. export async function POST({ request }) { const data = await request.json(); if (!data.name) { return { status: 404, body: { error: 'Name not found' } }; } return { status: 200, body: { message: `Welcome, ${data.name}` } }; }

Solution

  1. Step 1: Validate the 'name' field properly

    The correct snippet destructures { request }, checks if name exists, is a string, and non-empty after trim(), returning 400 if invalid.
  2. 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.
  3. Final Answer:

    The snippet with full validation (exists, string, trimmed non-empty) and 400 status -> Option A
  4. Quick Check:

    Validate input and return 400 if invalid [OK]
Hint: Check for empty or missing fields, return 400 for bad input [OK]
Common Mistakes:
  • Returning wrong status codes like 404 or 500 for validation errors
  • Throwing errors instead of returning HTTP responses
  • Not trimming strings before checking emptiness
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