0
0
Svelteframework~20 mins

Server routes (+server.js) in Svelte - Mini Project: Build & Apply

Choose your learning style9 modes available
Create a Simple Svelte Server Route with server.js
📖 Scenario: You are building a small web app using SvelteKit. You want to create a server route that returns a list of fruits as JSON data. This will help your frontend show the fruit list dynamically.
🎯 Goal: Build a SvelteKit server route using +server.js that returns a JSON response with a list of fruits.
📋 What You'll Learn
Create a server route file named +server.js
Define a GET handler function that returns a JSON response
Use an array of fruits as the data source
Return the fruits array in the response body with status 200
💡 Why This Matters
🌍 Real World
Server routes in SvelteKit let you build backend APIs easily inside your frontend project. This is useful for fetching data, handling forms, or connecting to databases.
💼 Career
Knowing how to create server routes is essential for full-stack SvelteKit developers. It helps you build dynamic web apps that communicate between frontend and backend smoothly.
Progress0 / 4 steps
1
Set up the fruits data array
Create a constant array called fruits with these exact string values: "apple", "banana", "cherry".
Svelte
Hint

Use const fruits = ["apple", "banana", "cherry"] to create the array.

2
Create the GET handler function
Add an exported async function named GET that takes a single parameter {} (an empty object).
Svelte
Hint

Write export async function GET({}) { } to define the route handler.

3
Return the fruits array as JSON response
Inside the GET function, return a new Response object with the JSON stringified fruits array as the body, and set the header Content-Type to application/json. Use status code 200.
Svelte
Hint

Use return new Response(JSON.stringify(fruits), { status: 200, headers: { 'Content-Type': 'application/json' } }).

4
Complete the +server.js file
Ensure the entire +server.js file contains the fruits array and the exported async GET function returning the JSON response exactly as shown.
Svelte
Hint

Check that the file has the fruits array and the GET function returning the JSON response.