본문으로 건너뛰기

레슨 25 · SvelteKit

Hooks and Server Endpoints in SvelteKit

Use SvelteKit hooks (handle, handleError, handleFetch) for auth and logging, chain them with sequence, and build JSON API routes with +server.js and RequestHandlers.

Pages and forms cover most of an app, but two more tools make a SvelteKit project feel complete. Hooks run code for every request: reading a session cookie, adding security headers, logging errors. Endpoints (+server.js) are routes that return data instead of HTML: a JSON API, an RSS feed, a webhook receiver.

SvelteKit is read-only on this site. The <TryIt> blocks are stand-ins in plain JavaScript that model hooks as a middleware chain and endpoints as request handlers on the standard Request and Response objects, which really do exist in the browser and Node.

The handle hook

Create src/hooks.server.js. Its handle function wraps each request; resolve(event) renders the route:

JavaScript
// src/hooks.server.js
export async function handle({ event, resolve }) {
  const token = event.cookies.get('session');
  event.locals.user = token ? await getUserBySession(token) : null;

  if (event.url.pathname.startsWith('/admin') && event.locals.user?.role !== 'admin') {
    return new Response('Forbidden', { status: 403 });
  }

  const response = await resolve(event);
  response.headers.set('X-Frame-Options', 'DENY');
  return response;
}

Anything you put on event.locals is visible to every server load, action and endpoint for that request. That is the standard way to pass the signed-in user around; add its type to App.Locals in src/app.d.ts when you use TypeScript.

resolve accepts options such as transformPageChunk to rewrite the HTML (set <html lang>), and filterSerializedResponseHeaders. Remember that code before resolve runs before routing and load; code after it can change the response.

Chaining with sequence

For several concerns, write small hooks and combine them with sequence:

JavaScript
import { sequence } from '@sveltejs/kit/hooks';

const logger = async ({ event, resolve }) => {
  const start = performance.now();
  const response = await resolve(event);
  console.log(`${event.request.method} ${event.url.pathname} ${response.status} ${Math.round(performance.now() - start)}ms`);
  return response;
};

const auth = async ({ event, resolve }) => { /* set locals.user */ return resolve(event); };

export const handle = sequence(logger, auth);

Hooks run in order on the way in and in reverse on the way out, like onion layers.

JS A hook chain like sequence()

Press Run (or Ctrl + Enter) to see the console output here.

No output.

handleError and handleFetch

handleError receives unexpected errors (anything thrown that is not error() or redirect()). Log them and return a safe message; never leak stack traces to users:

JavaScript
export function handleError({ error, event, status, message }) {
  const id = crypto.randomUUID();
  console.error(id, event.url.pathname, error);
  return { message: 'Something went wrong.', id };
}

The returned object becomes page.error in +error.svelte, so you can show "reference: ..." for support.

handleFetch intercepts fetch calls made inside server load functions, useful to point public API URLs at an internal address or to attach credentials:

JavaScript
export async function handleFetch({ request, fetch }) {
  if (request.url.startsWith('https://api.example.com/')) {
    request.headers.set('Authorization', `Bearer ${API_TOKEN}`);
  }
  return fetch(request);
}

Endpoints with +server.js

A +server.js file exports a function per HTTP verb: GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS. Each receives the request event and returns a standard Response.

JavaScript
// src/routes/api/todos/+server.js
import { json, error } from '@sveltejs/kit';
import { listTodos, createTodo } from '$lib/server/todos';

export async function GET({ url, locals }) {
  if (!locals.user) error(401, 'Sign in first');
  const limit = Math.min(Number(url.searchParams.get('limit') ?? 20), 100);
  return json(await listTodos(locals.user.id, limit));
}

export async function POST({ request, locals }) {
  const body = await request.json();
  if (typeof body.text !== 'string' || body.text.length < 3) {
    return json({ message: 'text must be at least 3 characters' }, { status: 400 });
  }
  const todo = await createTodo(locals.user.id, body.text);
  return json(todo, { status: 201 });
}

json() from @sveltejs/kit is a shortcut for new Response(JSON.stringify(...), { headers: { 'content-type': 'application/json' } }). For anything else, build a Response yourself: an RSS feed, a CSV download, an image.

JavaScript
// src/routes/rss.xml/+server.js
export const prerender = true;

export async function GET() {
  const xml = `<?xml version="1.0"?><rss version="2.0"><channel><title>My blog</title></channel></rss>`;
  return new Response(xml, { headers: { 'Content-Type': 'application/xml' } });
}

Dynamic segments work as in pages: src/routes/api/todos/[id]/+server.js receives params.id. If a route folder has both +page.svelte and +server.js, SvelteKit sends browser page requests (Accept: text/html) to the page and other GET requests to the endpoint; non-GET verbs go to the endpoint (or to form actions).

Endpoints as plain handlers

Because endpoints work with standard Request/Response, you can run a router of handlers right here:

JS Verb handlers on Request and Response

Press Run (or Ctrl + Enter) to see the console output here.

No output.

When to use what

Need Tool
Data for a page load
Handle a form POST from your own pages form action
JSON for a mobile app or third-party client +server.js
Webhook from Stripe or GitHub +server.js POST
Cross-cutting concerns (auth, headers, logging) hooks.server.js

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. What does event.locals hold?

    locals is a plain object scoped to one request; the usual place to store the current user after reading a session cookie.
  2. 2. Which function wraps several handle hooks into one?

    sequence comes from @sveltejs/kit/hooks and runs hooks in order, nested like layers.
  3. 3. What must a +server.js handler return?

    Handlers return a standard Response; json() is a helper that builds one.
  4. 4. Which hook receives unexpected errors so you can log them?

    handleError is for thrown errors that are not error() or redirect(); the object it returns becomes page.error.

Summary

  • src/hooks.server.js exports handle (every request), handleError and handleFetch; use event.locals to pass the current user around.
  • sequence() chains hooks like onion layers.
  • +server.js exports one function per HTTP verb returning a standard Response; json() is the shortcut.
  • Use load for page data, actions for your own forms and endpoints for APIs and webhooks.

Next: Rendering Modes and Deployment

진행 상황 기록

무료 계정을 만들면 레슨을 체크하고, 어떤 기기에서든 하던 곳부터 이어 학습할 수 있어요.