| | |

Svelte 65 🧡 API Endpoints — Request Handlers (+server.ts)

⏱️ Estimated read: 8 min | |

SvelteKit is a full-stack framework, meaning you aren’t limited to rendering UI; you can also build production-grade API backends directly within your project. While +page.server.ts files handle Form Actions and page data, +server.ts files allow you to define custom API endpoints. These files act as standard request handlers, responding to HTTP methods like GET, POST, PUT, PATCH, and DELETE with full control over the Response object.

By keeping your API endpoints within the same filesystem as your frontend, you eliminate the need for cross-origin resource sharing (CORS) configurations, simplify deployment, and allow your frontend to share logic, types, and utilities with your backend seamlessly. This chapter explores how to define request handlers, parse incoming requests, and return properly formatted JSON or standard responses.

Key point: +server.ts files define custom API endpoints where you export functions named after HTTP verbs (e.g., GET, POST); these functions accept a RequestEvent and must return a Response object, providing full control over the server-side API interface.


Why exists

The Backend/Frontend Unity Problem. Traditionally, web apps require a frontend repository and a backend repository, leading to fragmented types and constant API-layer maintenance. +server.ts exists to unify these environments, allowing you to move data between layers with zero friction.

The CORS Complexity Problem. Calling an external API from the browser often involves complex CORS negotiation. +server.ts endpoints run on the same origin as your app, meaning browsers treat them as local calls, removing the need for Access-Control-Allow-Origin headers.

The Performance Problem. Fetching data from a separate server adds latency due to DNS resolution and handshakes. Endpoints in +server.ts run within the same infrastructure as your application, often allowing for “server-side fetches” that bypass the network entirely when the server handles the request.

The Proxy Need Problem. For security or API key protection, developers often write “proxy” servers. +server.ts acts as a native proxy, allowing you to hide internal API keys from the browser while exposing a clean, public-facing endpoint for your frontend components.

The Type-Safety Problem. By keeping your API logic in the same codebase as your frontend, you can import your TypeScript interfaces directly, ensuring that the backend response structure is always in sync with your frontend consumption.


a. The HTTP Method Handler Signature

Every +server.ts file acts as a controller for a specific route. You define functionality by exporting functions named after the desired HTTP method. These functions receive a RequestEvent, which contains everything you need—from URL parameters and headers to body content and request cookies.

// src/routes/api/products/+server.ts
import { json } from '@sveltejs/kit';

export async function GET() {
  const products = await fetchFromDB();
  return json(products);
}

export async function POST({ request }) {
  const body = await request.json();
  const created = await saveToDB(body);
  return json(created, { status: 201 });
}

The function name MUST be in uppercase (e.g., GET, POST). If you define a route that doesn’t export a matching method (e.g., sending a DELETE request to a route that only exports GET), SvelteKit will automatically return a 405 Method Not Allowed response, saving you from writing manual error checking.


b. Returning Responses and JSON

SvelteKit provides a json() helper that streamlines the creation of JSON-based Response objects. While you can return any standard Response object (allowing you to stream data, return files, or provide raw text), the json() helper is the standard for building JSON APIs because it automatically sets the Content-Type: application/json header.

import { json } from '@sveltejs/kit';

export async function GET() {
  // Use json() for standard API responses
  return json({ message: 'Success', status: 200 });
}

export async function GET_RAW() {
  // Use standard Response for raw data, XML, or streams
  return new Response('Hello World', {
    headers: { 'Content-Type': 'text/plain' }
  });
}

Returning custom headers is also straightforward. You can create a new Response object and pass a configuration object as the second argument, setting headers like Cache-Control, Set-Cookie, or security policies. This gives you complete control over the HTTP communication channel.


c. Parsing Request Bodies and Headers

The request property in the RequestEvent allows you to access the payload of the request. Since +server.ts is a raw server handler, you are responsible for parsing the body content (e.g., await request.json() for JSON, or await request.formData() for form data).

export async function PUT({ request, params }) {
  const { id } = params;
  const data = await request.json();

  if (!data.name) {
    return json({ error: 'Name is required' }, { status: 400 });
  }

  await updateProduct(id, data);
  return json({ success: true });
}

You can also use the cookies object (e.g., cookies.get('session')) or the request.headers object to inspect authentication tokens or custom metadata. This setup allows you to build sophisticated middleware-like logic for your API endpoints by validating the environment before performing your business operations.


Complete Example Session

// ============================================
// PART 1: GET REQUEST
// ============================================
// src/routes/api/user/[id]/+server.ts
export const GET = ({ params }) => {
  return json({ id: params.id });
};

// ============================================
// PART 2: POST REQUEST
// ============================================
export const POST = async ({ request }) => {
  const body = await request.json();
  return json(body, { status: 201 });
};

// ============================================
// PART 3: DELETE REQUEST
// ============================================
export const DELETE = async ({ params }) => {
  await db.delete(params.id);
  return new Response(null, { status: 204 });
};

// ============================================
// PART 4: JSON HELPER
// ============================================
// import { json } from '@sveltejs/kit';

// ============================================
// PART 5: REQUEST PARSING
// ============================================
// const data = await request.formData();

// ============================================
// PART 6: HEADERS CONTROL
// ============================================
// return json(data, { headers: { 'Cache-Control': 'max-age=60' } });

// ============================================
// PART 7: COOKIE ACCESS
// ============================================
// const session = cookies.get('session');

// ============================================
// PART 8: ERROR HANDLING
// ============================================
// return json({ error: 'Fail' }, { status: 400 });

// ============================================
// PART 9: URL ACCESS
// ============================================
// const searchParams = url.searchParams;

// ============================================
// PART 10: METHOD NOT ALLOWED
// ============================================
// SvelteKit automatically handles this!

These parts illustrate the full lifecycle of a CRUD-based API endpoint handler.


Quick Reference

Method Export Names

VerbPurpose
GETRetrieve resources
POSTCreate resources
PUTReplace resources
PATCHUpdate part of a resource
DELETERemove resources

Helper Utilities

UtilityPurpose
json(data)Return JSON object
Response(body, init)Return raw HTTP Response
request.json()Parse body as JSON
cookies.get/setManage cookies

Best Practices

✅ Do This:

// Use the json helper for JSON APIs
return json({ success: true });                            // ✅

// Explicitly set status codes for success
return json(data, { status: 201 });                        // ✅

// Handle errors with JSON responses
return json({ error: 'Auth failed' }, { status: 401 });    // ✅

// Use relative URL paths for internal requests
const data = await fetch('/api/other');                    // ✅

❌ Don’t Do This:

// Don't return raw objects (must be Response)
return { data: 1 }; // (Will cause runtime error)       // ❌

// Don't leak private keys to the client
return json({ key: PRIVATE_KEY }); // (Security breach)   // ❌

// Don't forget to await request.json()
const data = request.json(); // (Returns a promise)       // ❌

// Don't try to access server-side db in +page.svelte
// Use +server.ts or +page.server.ts instead               // ❌

Common Pitfalls

PitfallWhy It HappensFix
405 ErrorMethod not exportedExport matching method
[object Promise]Forgot await on bodyAdd await
Invalid JSONPayload is not valid JSONValidate input
CORS issueUsing fetch for externalEnsure same-origin calls

Real-World Examples

1. Basic JSON endpoint

export const GET = () => json({ status: 'ok' });

2. POST with body

export const POST = async ({ request }) => {
  const data = await request.json();
  return json(data, { status: 201 });
};

3. Delete record

export const DELETE = ({ params }) => { ... return new Response(null, { status: 204 }); };

4. Setting headers

return json(data, { headers: { 'X-Custom': 'header' } });

5. Cookie auth

const session = cookies.get('sid');

6. Handling query params

const limit = url.searchParams.get('limit');

7. Raw response

return new Response('File content', { headers: { 'Content-Type': 'text/csv' } });

8. Validation check

if (!auth) return json({ err: 'No auth' }, { status: 401 });

9. Returning a status

return json({}, { status: 200 });

10. Async logic

const data = await getDbData();

Visual

Request Handler Lifecycle

┌──────────────────────────────────────┐
│  Client: HTTP Request                │
│       │                              │
│  SvelteKit: Match Route -> Handler   │
│       │                              │
│  Handler: Logic -> Response Object   │
│       │                              │
│  Client: Receives Response           │
└──────────────────────────────────────┘

Method Routing

┌──────────────────────────────────────┐
│  Request: GET /api/data              │
│       │                              │
│  Look for export GET                 │
│       │                              │
│  Found? Exec & Return Response       │
│  No? 405 Method Not Allowed          │
└──────────────────────────────────────┘

Summary

ItemValue
Filename+server.ts
ExportGET, POST, PUT, DELETE
Helperjson()
InputRequestEvent
LogicFull server-side power

Key takeaways:

  • Standard HTTP verbs. Endpoints are defined by exporting functions named after standard HTTP methods, making the API surface predictable and RESTful.
  • Unified infrastructure. Building APIs within SvelteKit allows you to share types and utilities between your frontend and backend.
  • The json() helper is your best friend. Use it to ensure correct headers and serialized output for all JSON-based API responses.
  • Control the Response. Since you return a native Response object, you have full control over status codes, headers, and body content for every request.
  • Internal fetch. Always prefer calling your own +server.ts routes via fetch inside load functions to maintain performance and cookie authentication.

Remember: API endpoints in SvelteKit provide a sophisticated backend layer that is perfectly colocated with your frontend logic. By following the standard HTTP patterns, you can create a powerful API interface that is type-safe, performant, and simple to manage within the same project.

Was this helpful?


Stop using slow, ad-bloated tool sites! 🤮

🔎 Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)

⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free

🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!