Skip to content

v0.8.0: index.ts is the route, on both sides

6 min read

A minor release with one change at its heart, and a breaking one: index.ts is now the route identity on the frontend, as it has always been on the backend.

index.ts defines the route. page.<ext> renders it.

Custom templates change along with it, and break too: they become directories, with one template file for each file a route seeds.

The same route file also becomes the place for page validation and staticParams. Fetch clients start loading on demand, and an optional cacheDir keeps resolved types between builds.

One file to declare a route ​

Until now, a page route was its component: pages/users/[id]/index.tsx was the route and its page at once. The backend has always worked the other way, with api/users/[id]/index.ts declaring the route.

Now both sides declare a route the same way:

txt
api/
  users/
    [id]/
      index.ts      -> /api/users/:id
pages/
  users/
    [id]/
      index.ts      -> /users/:id
      page.tsx      -> renders it

A page route's index.ts is plain TypeScript, whatever the framework, and it only declares the route:

pages/users/[id]/index.ts
ts
import { defineRoute } from "_/pages";

export default defineRoute<"users/[id]">();

defineRoute takes the route name as a type argument, and defines nothing at runtime. Its optional type arguments are the route's contract: the params it accepts and the query it expects.

The same file also carries staticParams for SSG, covered below.

page.* renders it ​

The component moves next to it, into the page file:

ReactSolidVueSvelteMDX
Pagepage.tsxpage.tsxpage.vuepage.sveltepage.mdx
Layoutlayout.tsxlayout.tsxlayout.vuelayout.sveltelayout.mdx

Everything the page itself owns stays in the page file - the component and loader (preload in Solid). Layouts do not change at all.

page.* and layout.* are the route's assets, not routes of their own: delete the index.ts, and the folder is no longer a route, whatever else is in it.

Seeded as before ​

Create an empty index.ts, and the dev server seeds it with the route definition, along with a page file holding the framework's boilerplate.

Details ›

Validation is part of the route ​

Until now, page params and query arrived as raw strings and were checked, if at all, inside the component.

The route file can now declare them as types, and KosmoJS derives the runtime schema from the same declaration:

pages/users/[id]/index.ts
ts
import { defineRoute } from "_/pages";

export default defineRoute<
  "users/[id]",
  [number],
  { tab?: "profile" | "posts" }
>();

The second type argument is a tuple refining the route's params in path order. The third is the query shape itself - there is no { query: ... } wrapper, because a page only validates what the router hands it.

Both stay inline: the tuple and the object are read structurally from the source. Both are checked on the server and in the browser, before the page component mounts.

Values are coerced before checking, with the same rules as the backend: a param typed as number becomes a number, and query keys typed as number or boolean are converted the same way.

The query object stays open to parameters the route does not declare; browsers, proxies and analytics add those, and they should not fail a page.

The page reads the validated result through useParams() and useSearchParams() from _/use; the framework's own hooks still return the router's raw values.

A failed check is an operational error, not a broken render. The nearest error.<ext> file beside an index.ts renders it - ValidationError for params or query, FetchError for a failed loader or fetch client, HTTPError when application code throws one.

One error file covers its route and everything below it.

Validation is wired when the folder's validation option is on - the default for new folders. Frontend validation › · Error files ›

staticParams moves into index.ts ​

Static params used to live wherever each framework allowed a named export: the page module for React and Solid, a plain script block for Vue, a module script for Svelte, frontmatter for MDX.

They now live in the route's index.ts, and look the same everywhere:

pages/docs/[slug]/index.ts
ts
import { defineRoute, defineStaticParams } from "_/pages";

export const staticParams = defineStaticParams<"docs/[slug]">([
  ["getting-started"],
  ["routing"],
]);

export default defineRoute<"docs/[slug]">();

Each entry is positional in the route's parameter order.

A splat takes an array of segments, and numbers are stringified into the path - on a route like items/[id], [[1], [2]] renders items/1 and items/2.

A static route renders without one; a dynamic route without staticParams is skipped rather than guessed. The page's loader (preload in Solid) runs once per variant, against the API bundled into the SSR server.

Besides making SSG the same on every stack, this keeps page.* a page: its component and data loader, nothing the build has to find by convention. Static generation ›

Fetch clients load on demand ​

_/fetch no longer imports every route's client when the map is imported. Each entry is a small wrapper that dynamic-imports its client on the first call:

pages/example/page.tsx
ts
import fetchClients from "_/fetch";

const { GET } = fetchClients["users/[id]"];

const user = await GET([123]); // this route's client loads now

loadValidationSchemas() is lazy in the same way: a route's schemas load when you ask for them, not with the map. Importing _/fetch costs the map itself, not the API surface behind it.

The call site and the types do not change. Params, payload and response still come from the route definition, and client-side validation still runs before the request leaves the browser.

What changes is when the code arrives: a page that calls one endpoint no longer downloads the client for every other route. Fetch clients ›

A type cache you can commit ​

Resolving a route's types means parsing the route, following every type import it reaches and evaluating the result.

By default that happens on every build. For a project with hundreds of routes it is still only seconds, but it is a pass you can skip:

src/app/kosmo.config.ts
ts
import { defineConfig } from "@kosmojs/dev";

export default defineConfig({
  // ...
  cacheDir: "cache",
});

cacheDir is relative to the folder's config. Resolved types are written per route under <cacheDir>/<api|pages>/<route>/typemap.json, keyed by the route file and every file its types reference. Change either, and that route - not the whole project - is resolved again.

The cache stores relative paths and content hashes, so it survives clones, CI runs and different machines; commit it with the project.

var/lib/ stays disposable - the cache is the durable part, and only when you ask for it. Deleting the directory, or a KosmoJS cache-version bump, forces a full derivation pass.

Configuration ›

Templates are directories ​

The templates option took a template string, or a function returning one, written inside kosmo.config.ts. A function also told the files of a route apart by kind.

Now a pattern points at a directory, and the directory holds one file for each file a route seeds:

txt
src/front/
  kosmo.config.ts
  templates/
    admin/
      index.tpl
      page.tpl
      layout.tpl
      error.tpl
src/front/kosmo.config.ts
ts
export default defineConfig({
  frontend: {
    stack: "react",
    base: "/front",
    templates: {
      "admin/**": "templates/admin",
    },
  },
});

On the frontend, that is index.tpl for the route's index.ts, page.tpl for its page file, layout.tpl for a layout and error.tpl for error pages.

On the backend, index.tpl for the route's index.ts, and use.tpl for a use.ts.

Each file is optional: one the directory does not hold gets the built-in boilerplate. Paths are relative to the kosmo.config.ts itself.

Each file is rendered with Handlebars, with the route entry itself as the context, so {{name}} interpolates the route name.

Frontend › · Backend ›

Upgrading ​

Rename every page index.<ext> to page.<ext>, and put an empty index.ts beside it - the next start seeds it.

MDX folders take page.mdx only, and ignore a page.md, so an index.md page becomes page.mdx.

From the project root, with bash:

sh
shopt -s globstar nullglob
for f in src/*/pages/**/index.{tsx,vue,svelte,mdx,md}; do
  ext="${f##*.}"
  [ "$ext" = md ] && ext=mdx
  git mv "$f" "${f%/*}/page.$ext"
  touch "${f%/*}/index.ts"
done

Route names, URLs, typed links and layouts stay as they were.

staticParams ​

Move staticParams from each page file into its sibling index.ts, importing defineStaticParams from _/pages. MDX pages move it out of frontmatter and into the same export. Values and their order do not change.

Validation ​

Nothing is required. To opt a page in, add the params tuple and query shape to its defineRoute and read the validated values through _/use. Pages without type arguments behave as before: index.ts still declares the route, but no runtime schema is wired.

Fetch clients ​

No changes at the call site. _/fetch keeps the same shape and types; the route's client is imported the first time one of its methods is called, and loadValidationSchemas() loads that route's schemas on first use.

cacheDir ​

Opt-in, per folder. Add cacheDir to kosmo.config.ts and commit that directory to reuse resolved types across builds; omit it to keep resolving types on every build.

Templates ​

Move each template into a directory of its own, as a file named after what it seeds: a page template into page.tpl, a layout into layout.tpl, a backend route into index.tpl, a use.ts into use.tpl. Then replace the template in templates with the directory's path:

kosmo.config.ts
ts
templates: {
  "admin/**": adminTemplate,
  "admin/**": "templates/admin",
},

A function that returned a different template per kind becomes one directory with several files.

Inside the files, {{route.name}} becomes {{name}}: the route entry itself is the context now.

Released under the MIT License.