Skip to content

@ogygia/router

Pages and layouts

page() pairs a Svelte component with what a +page.server.ts would hold, and layout() wraps a group of routes in a shared component, load and error page. A router page renders as a csr = false ogygia document, with islands, regions and $app/state working as on any ogygia page.

On this page

In Kit, a page is two or three files side by side, and a layout is a file in a parent folder. In a table, each is one call. A page is a component plus its server side: page(Component, server) takes the component first and, second, an object shaped like a +page.server.ts: its load, its actions, and a few options. When there’s nothing to declare, write page(Home).

A layout wraps a group of routes. layout(name, Component, options) returns a function: apply it to a table and every page in that table renders inside the layout, with its load’s data merged in.

import { routes, page, layout } from '@ogygia/router';
import Shell from '$lib/views/Shell.svelte';
import Home from '$lib/views/Home.svelte';
import About from '$lib/views/About.svelte';
import { auth } from '$lib/server/auth';

const app = layout('app', Shell, {
  load: async (c) => ({ user: await auth.user(c.cookies) })
});

export const router = routes(
  app({
    '/': page(Home),
    '/about': page(About)
  })
);

export type App = typeof router.$infer;

Declaring pages

The second argument of page() takes these keys. All of them are optional.

KeyWhat it isCovered in
loadThe page’s load: a function of c that returns its data.Loading data
actionsForm actions, keyed by name, default for the unnamed one.Form actions
paramsA Standard Schema that coerces and checks the path params. A miss answers 404.Typed params
searchA Standard Schema for the query string. A miss answers 400.Typed query
entriesThe param sets of a dynamic route to prerender, Kit’s entries.Prerender
configKit’s config page option, read by plugins.config
import { routes, page } from '@ogygia/router';
import * as v from 'valibot';
import Editor from '$lib/views/Editor.svelte';
import { posts } from '$lib/server/posts';

export const router = routes({
  '/edit/[id]': page(Editor, {
    params: v.object({
      id: v.pipe(v.string(), v.toNumber(), v.integer())
    }),
    load: async (c) => ({
      post: await posts.byId(c.params.id)
    }),
    actions: {
      save: async (c) => {
        await posts.save(
          c.params.id,
          await c.request.formData()
        );
        return { saved: true };
      }
    },
    config: { postrender: false }
  })
});

Props

The page component gets three props, as a Kit +page.svelte does:

  • data: the merged data of every load on its branch, from the table-wide load through each layout to the page.
  • form: what the action returned, after a POST. It’s undefined on a GET.
  • params: the route’s params, or the params schema’s output.

Type them with App['/path'], the route’s key indexed into the table’s App type. There’s no search prop; see Type the query string.

<script lang="ts">
  import type { App } from '$lib/router';

  let {
    data,
    form,
    params
  }: App['/edit/[id]'] = $props();
</script>

<h1>Editing post {params.id}</h1>
{#if form?.saved}<p>Saved.</p>{/if}
<form method="POST" action="?/save">
  <textarea name="body">{data.post.body}</textarea>
  <button>Save</button>
</form>

Components

The first argument of page() is usually a component. It can also be:

  • A component imported with wake. The whole page is then one island, hydrated with its props. Use it for a page that’s all interaction, like a board or an editor.
  • A component imported with render: 'deferred'. The whole page is then a server island: the document goes out with an empty hole, and the browser fetches the page’s HTML, rendered with its props, right after. page() has no way to give it a loading placeholder, so the hole stays empty until then. For a loading state, keep the page a plain component and put the deferred island, with its fallback, inside it.
  • A flag’s pick(). page(hero.pick({ control: Hero, bold: HeroBold })) renders the variant the visitor is in. See Page variants.
  • An async generator. The page flushes its first yield at once and swaps in the rest. See Streaming.

A route can also be a federation mount(peer) in place of page(), which renders another team’s app inside your layouts: '/cms/[...rest]': mount(cms). See Mounting apps.

import { routes, page } from '@ogygia/router';
import Board from '$lib/views/Board.svelte' with {
  wake: 'load'
};
import Hero from '$lib/views/Hero.svelte';
import HeroBold from '$lib/views/HeroBold.svelte';
import { hero } from '$lib/flags';
import { boards } from '$lib/server/boards';

export const router = routes({
  '/': page(hero.pick({ control: Hero, bold: HeroBold })),
  '/board/[id]': page(Board, {
    load: async (c) => ({
      board: await boards.get(c.params.id)
    })
  })
});

Layouts

layout(name, Component, { load, error, config }) is Kit’s +layout.svelte with its server load. Apply it to a table, and every page inside renders within the layout. The result is a table with the same keys, so you can pass it to routes() or spread it into a bigger table.

  • load runs for every page inside, at the same time as the page’s own load. Its data merges into theirs. See Loading data.
  • error is the error page for the routes inside. See Error pages.
  • config sets config keys for every page inside.

The layout component gets data and children, like a Kit layout, and renders {@render children()} where the page goes. Type its props with App['(name)']: the name in parentheses, like a Kit group. Its data is typed as what this layout’s load and every layout around it return; at run time it’s the page’s whole merged data, so it holds more than the type says.

A layout’s name keys its type, so layouts with different components can’t share one: routes() throws when the table is built if they do. Applying the same layout value in several places is fine.

Nest layouts

A nested layout is a wrapped table spread into another. A page inside both renders inside both components, outermost first, and its data merges both loads with its own.

Break out of a layout

Kit resets a page to an outer layout with +page@name.svelte, or to none with +page@.svelte. Here, you place the route in the table wrapped by exactly the layouts you want. No annotation is needed.

<script lang="ts">
  import type { App } from '$lib/router';
  import '$lib/styles/app.css';

  let { data, children }: App['(app)'] = $props();
</script>

<header>Signed in as {data.user.name}</header>
<main>{@render children()}</main>
import { routes, page, layout } from '@ogygia/router';
import Shell from '$lib/views/Shell.svelte';
import DashShell from '$lib/views/DashShell.svelte';
import Home from '$lib/views/Home.svelte';
import Dashboard from '$lib/views/Dashboard.svelte';
import { auth } from '$lib/server/auth';
import { teams } from '$lib/server/teams';

const app = layout('app', Shell, {
  load: async (c) => ({ user: await auth.user(c.cookies) })
});
const dash = layout('dash', DashShell, {
  load: async (c) => ({ team: await teams.of(c.cookies) })
});

export const router = routes(
  app({
    '/': page(Home), // Shell
    ...dash({
      '/dashboard': page(Dashboard) // Shell › DashShell, data: { user, team }
    })
  })
);
import { routes, page, layout } from '@ogygia/router';
import Shell from '$lib/views/Shell.svelte';
import DashShell from '$lib/views/DashShell.svelte';
import Dashboard from '$lib/views/Dashboard.svelte';
import Settings from '$lib/views/Settings.svelte';
import Login from '$lib/views/Login.svelte';

const app = layout('app', Shell);
const dash = layout('dash', DashShell);

export const router = routes({
  ...app({
    ...dash({ '/dashboard': page(Dashboard) }), // app › dash
    '/dashboard/settings': page(Settings) // app only, like +page@(app)
  }),
  '/login': page(Login) // no layout, like +page@
});

Islands, regions and page state

A router page renders as an ogygia document, the same kind of page as a Kit route with csr = false. Kit’s client never loads on it. The page is server HTML, and only marked imports inside it run in the browser: client islands with wake, server islands with render: 'deferred', and held regions with <Region>.

page from $app/state works on router pages. On the server, every component reads the page’s data, params, url, route.id, status, form and error. In an island, it reads the same values from the page seed, which ships only when an island reads page; with dataShake() it ships only the keys islands read. route.id is the route’s pattern, like /posts/[slug].

To stream a slow part of the page, see Streaming. A promise of plain data in a load doesn’t stream into islands as it does on a Kit page.

The SPA router moves between router pages, and between router pages and csr = false Kit pages, by swapping the body. goto(), invalidateAll() and the rest of $app/navigation work in islands. A page with no islands still gets the SPA router.

In an island, page.data isn’t typed by the table; see Where inference stops.

<script lang="ts">
  import { page } from '$app/state';
</script>

<p>
  Hello, {page.data.user?.name ?? 'guest'}. You're on {page
    .route.id}.
</p>

A router page isn’t rendered from your app.html. It gets ogygia’s own document: <html lang="en">, a UTF-8 charset, a width=device-width viewport, the head your components write, and the runtime. So anything your app.html adds must come from a component:

  • Set the title and meta tags with <svelte:head>, in the page or a layout.
  • Import global CSS from a layout component, as Shell.svelte above does with app.css. The router() plugin links every stylesheet a page’s components reach, scoped styles and .css imports alike.
  • Fonts, icons and other <link> tags go in a layout’s <svelte:head>.

The lang attribute is always en on a router page; there’s no option to change it yet (#2293).

A page response carries cache-control: no-store, unless postrender stores it. Whether c.setHeaders() can replace it depends on how the table is served.

Page options

config is Kit’s config page option: the router’s form of export const config = { … } in a +page.server.ts. Plugins read their own keys from it. Postrender reads postrender to decide which pages it stores.

Set it at three levels. They merge as in Kit: the table first, then each layout from the outermost in, then the page. A later level replaces a key of the same name, top-level keys only. Endpoints have no config.

Keep ogygia.handle() ahead of router.handle in sequence(). ogygia’s handle reads a table’s config for any request Kit’s file routes didn’t claim, so a page postrender stored is served before the table runs.

import { routes, page, layout } from '@ogygia/router';
import Shell from '$lib/views/Shell.svelte';
import Home from '$lib/views/Home.svelte';
import Pricing from '$lib/views/Pricing.svelte';
import Account from '$lib/views/Account.svelte';

const marketing = layout('marketing', Shell, {
config: { postrender: true }
});

export const router = routes(
  {
    ...marketing({
      '/': page(Home),
      '/pricing': page(Pricing)
    }),
    '/account': page(Account, {
    config: { postrender: false }
    })
  },
  { config: { postrender: false } }
);