# +server.ts Routes and Hooks — Svelte / SvelteKit

Source: https://www.skillbyai.com/en/svelte/d-endpoints

> HTTP handlers, handle and locals.

## Endpoints and the handle hook

A `+server.ts` file exports functions named after HTTP methods (`GET`, `POST`, `PUT`, `PATCH`, `DELETE`, ...). Each receives a `RequestEvent` and returns a standard `Response`; the `json()` helper from `@sveltejs/kit` builds JSON responses. Use endpoints for webhooks, JSON APIs consumed by other clients, or file downloads. `src/hooks.server.ts` exports `handle({ event, resolve })`, which runs for **every** request before routing: a common pattern reads a session cookie, looks up the user and stores it on `event.locals`, which load functions, actions and endpoints can then read. Type `locals` in `src/app.d.ts`. Combine several handle functions with `sequence` from `@sveltejs/kit/hooks`; `handleError` logs unexpected errors.

## Auth in handle, a JSON endpoint

hooks.server.ts, app.d.ts and +server.ts.

```typescript
// src/app.d.ts
declare global {
  namespace App {
    interface Locals { user: { id: string; name: string } | null }
  }
}
export {};

// src/hooks.server.ts
import type { Handle } from '@sveltejs/kit';
import { getUserBySession } from '$lib/server/auth';

export const handle: Handle = async ({ event, resolve }) => {
  const sid = event.cookies.get('sid');
  event.locals.user = sid ? await getUserBySession(sid) : null;
  return resolve(event);
};

// src/routes/api/todos/+server.ts
import { json, error } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import { db } from '$lib/server/db';

export const GET: RequestHandler = async ({ locals, url }) => {
  if (!locals.user) error(401, 'Sign in required');
  const limit = Number(url.searchParams.get('limit') ?? 20);
  return json(await db.todo.list(locals.user.id, Math.min(limit, 100)));
};
```

## Prefer actions for your own forms

Form actions give progressive enhancement and typed form results; +server.ts is better for APIs used by other clients or non-HTML responses.

**Quiz:** Where is the usual place to attach the current user for all server code?

- [ ] A global variable in a .svelte.ts module
- [x] event.locals inside the handle hook in hooks.server.ts
- [ ] The page component props
- [ ] localStorage

*Answer:* event.locals inside the handle hook in hooks.server.ts. locals is per request and safe on the server.
