0
0
Svelteframework~5 mins

Server routes (+server.js) in Svelte

Choose your learning style9 modes available
Introduction

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.

You want to get data from a database and send it to your webpage.
You need to save user input from a form to a server.
You want to create an API that other apps can use.
You want to handle login or signup actions securely.
You want to serve files or data without showing them in the browser URL.
Syntax
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.

Examples
A simple GET route that returns plain text.
Svelte
export async function GET() {
  return new Response('Hello world');
}
A POST route that reads JSON data sent by the client and responds with JSON.
Svelte
export async function POST({ request }) {
  const data = await request.json();
  return new Response(JSON.stringify({ received: data }), {
    headers: { 'Content-Type': 'application/json' }
  });
}
A DELETE route that confirms deletion.
Svelte
export async function DELETE() {
  return new Response('Deleted item');
}
Sample Program

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.

Svelte
// 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' }
  });
}
OutputSuccess
Important Notes

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.

Summary

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.