Skip to content

@ogygia/router

Endpoints

An endpoint is a table entry shaped like a +server.ts, an object of verb handlers. A plain return value is sent as JSON, a body schema validates what a POST sends, and api<App>() calls the endpoints from anywhere with typed paths, params, bodies and answers.

On this page

Not every URL is a page: an island fetches JSON, a feed reader wants text, another app calls your API. An endpoint answers with data instead of a page. In the table, it’s an object of handlers keyed by HTTP verb, the shape of a +server.ts. Each handler gets c, the request context, with c.params typed by the route’s key.

The handler’s return type is kept, so the typed client knows what each endpoint answers. That holds at the top of the table, inside layouts and behind when(). A layout’s load doesn’t run for an endpoint inside it; the table-wide load does.

import { routes } from '@ogygia/router';
import { posts } from '$lib/server/posts';

export const router = routes({
  '/api/posts/[id]': {
    GET: async (c) => posts.get(c.params.id),
    DELETE: async (c) => {
      await posts.remove(c.params.id);
      return new Response(null, { status: 204 });
    }
  }
});

export type App = typeof router.$infer;

Return values

  • A plain value is sent as JSON, with content-type: application/json and cache-control: no-store. Its type is what the typed client reads.
  • null or undefined answers 204 No Content.
  • A Response is sent as it is. Its payload is sealed inside, so the typed client reads unknown.

For a response with your own status or headers, c.json(data, init) and c.text(body, init) build one with the right content type; c.json also sets no-store unless you give a cache-control. Headers you pass win over these defaults. c.redirect(location, status) builds a redirect, 303 when you give no status. Prefer returning plain values where the client should see the type.

import { routes } from '@ogygia/router';
import { posts } from '$lib/server/posts';

export const router = routes({
  '/api/posts': {
    GET: async () => ({ posts: await posts.list() }) // typed JSON
  },
  '/feed.txt': {
    GET: async (c) =>
      c.text(await posts.digest(), {
        headers: { 'cache-control': 'max-age=300' }
      })
  }
});

HTTP methods

An endpoint takes GET, POST, PUT, PATCH, DELETE, HEAD and OPTIONS. Write only the ones you need:

  • A HEAD request runs the GET handler. A HEAD handler of your own is never called, so an endpoint with only HEAD answers 405 (#2293).
  • An OPTIONS request with no handler of its own answers 204 with an Allow header listing the verbs the endpoint has.
  • Any other verb it doesn’t have answers 405 with the same Allow header.

Validation

To type and check what a POST, PUT or PATCH sends, wrap the handler: POST(schema, handler). The schema is any Standard Schema (Valibot, Zod, ArkType). The router parses the JSON body, checks it, and puts the result on c.input, typed by the schema’s output. The handler runs only when the body passes.

  • A body that isn’t valid JSON answers 400 with { "error": "Invalid JSON body" }.
  • A body that fails the schema answers 400 with { "error": "Invalid body", "issues": [{ "message", "path" }] }.
  • A request whose content-type isn’t JSON is checked as an empty body, so it fails unless the schema allows undefined.

GET(fn) and DELETE(fn) take no schema, since those requests have no body: their input is the path and the query. { GET: GET(fn) } and { GET: fn } behave the same; the wrappers are there so every verb can be written alike. POST(fn), PUT(fn) and PATCH(fn) without a schema leave the body for you to read from c.request.

The query is c.search, an object of strings, first value per key. Endpoints have no search schema; check the query in the handler.

import { routes, POST, PUT } from '@ogygia/router';
import * as v from 'valibot';
import { posts } from '$lib/server/posts';

const NewPost = v.object({
  title: v.pipe(v.string(), v.minLength(1)),
  body: v.string()
});

export const router = routes({
  '/api/posts': {
    POST:POST(NewPost, async (c) =>
      posts.create(c.input)
    )// c.input: { title: string; body: string }
  },
  '/api/posts/[id]': {
    PUT: PUT(NewPost, async (c) =>
      posts.update(c.params.id, c.input)
    )
  }
});

Handlers outside the table

To keep a handler in its own file, check it with satisfies Handler<'/pattern'>. That types c.params and keeps the handler’s return type, which the typed client reads (why not an annotation).

Handler<'/pattern', Input> also types c.input, for a handler you pass to POST(schema, …) later.

import type { Handler } from '@ogygia/router';
import { posts } from '$lib/server/posts';

export const getPost = (async (c) =>
  posts.get(
    c.params.id
  )) satisfies Handler<'/api/posts/[id]'>;

Typed client

api<App>(base) from @ogygia/router/api is a fetch client built from your table’s App type. Its methods are the verbs in lowercase (get, post, put, patch, delete), and each one takes a route key, not a URL:

  • the paths it accepts are the keys that have that verb, so a page path or a missing verb is a type error;
  • params is required when the pattern has a required param, and fills the pattern as href() does;
  • body is typed from the schema of POST(schema, …), and sent as JSON;
  • search adds a query string, and headers adds headers to that call;
  • the answer is typed as the handler’s plain return value.

The module loads only the path grammar, nothing from the server, so an island can import it. App comes in with import type.

What the client does with an answer

  • A 204 resolves to undefined.
  • A 2xx with a JSON content type resolves to the parsed body; any other 2xx resolves to the text. A 2xx whose JSON doesn’t parse rejects.
  • Any other status throws ApiError, with status and body: the parsed JSON, or the text. A schema’s 400 carries its issues in body.

base is put in front of each path: '' for the same origin, or a full origin like https://cms.example.com for another app. Options on api() apply to every call: headers (an auth token, say) and fetch, for a test stub or a Kit event’s fetch on the server, which forwards cookies.

App for another app is that app’s typeof router.$infer, shared as a type through a package or a generated file. api and ApiError are also exported from @ogygia/router.

<script lang="ts">
  import { api, ApiError } from '@ogygia/router/api';
  import type { App } from '$lib/router';

  const client = api<App>('');
  let title = $state('');
  let message = $state('');

  async function create() {
    try {
      const post = await  client.post('/api/posts', {
        body: { title, body: '' }
      }); 
      message = `Created ${post.id}`;
    } catch (e) {
      message =
        e instanceof ApiError
          ? `Failed with ${e.status}`
          : 'Network error';
    }
  }
</script>

<input bind:value={title} />
<button onclick={create}>Create</button>
<p>{message}</p>
import { api } from '@ogygia/router/api';
import { env } from '$env/dynamic/private';
import type { App as Cms } from '$lib/cms-types';

export const cms = api<Cms>('https://cms.example.com', {
  headers: { authorization: `Bearer ${env.CMS_TOKEN}` }
});

export const draft = (id: string) =>
  cms.get('/api/posts/[id]', {
    params: { id },
    search: { draft: 1 }
  });