0
0
Svelteframework~5 mins

Response helpers (json, error) in Svelte

Choose your learning style9 modes available
Introduction

Response helpers make it easy to send data or errors back from your server code in a clear way.

When you want to send JSON data from a server endpoint to the client.
When you need to send an error message with a specific HTTP status code.
When you want to keep your server responses consistent and easy to read.
When building APIs or server routes that communicate with frontend components.
Syntax
Svelte
import { json, error } from '@sveltejs/kit';

// To send JSON data
return json(data, { status: 200 });

// To send an error response
throw error(statusCode, 'Error message');

The json helper formats your data as JSON and sets the right headers.

The error helper throws an error with a status code and message that SvelteKit understands.

Examples
This sends a JSON response with the message 'Hello world' and status 200 by default.
Svelte
import { json } from '@sveltejs/kit';

export function GET() {
  const data = { message: 'Hello world' };
  return json(data);
}
This throws a 404 error with the message 'Not found'. The client will receive this error response.
Svelte
import { error } from '@sveltejs/kit';

export function GET() {
  throw error(404, 'Not found');
}
This sends a JSON response with status 201, meaning a new resource was created.
Svelte
import { json } from '@sveltejs/kit';

export function POST() {
  const newItem = { id: 1, name: 'Item 1' };
  return json(newItem, { status: 201 });
}
Sample Program

This server GET handler checks for an 'id' query parameter. If missing, it throws a 400 error. Otherwise, it returns JSON data with the item info.

Svelte
import { json, error } from '@sveltejs/kit';

export function GET({ url }) {
  const id = url.searchParams.get('id');

  if (!id) {
    throw error(400, 'Missing id parameter');
  }

  const data = { id, name: `Item ${id}` };
  return json(data);
}
OutputSuccess
Important Notes

Always use throw error() to send error responses so SvelteKit can handle them properly.

The json() helper automatically sets the Content-Type header to application/json.

You can customize the HTTP status code in both helpers to match your API needs.

Summary

Use json() to send JSON data from server endpoints.

Use error() to throw HTTP errors with messages.

These helpers keep your server responses clear and consistent.