AbsoluteJS

File Routes

File routes turn files in a routes/ folder into GET routes for React and Svelte pages. A .server.ts file next to a page loads its props, and the types check that the two agree.

#Overview

File routes are opt-in. Explicit Elysia routes stay the default. Use file routes when an app has many content-shaped pages and you want the URL to follow the file path.

Each file route is a real Elysia GET route. Hooks and plugins registered before it, such as auth or secureHeaders(), apply to it like any other route.

#Enable File Routes

Set fileRoutes: true in absolute.config.ts.

TS
// absolute.config.ts
import { defineConfig } from '@absolutejs/absolute';

export default defineConfig({
  reactDirectory: 'src/frontend/react',
  svelteDirectory: 'src/frontend/svelte',
  fileRoutes: true
});

Pass an object instead to change the folder name or where the route module is written.

TS
fileRoutes: {
  // Folder inside each framework directory. Default 'routes'.
  directory: 'routes',
  // Where the generated route module is written. Default 'src/routes.gen.ts'.
  output: 'src/routes.gen.ts'
}

#The routes Folder

Route files live in a routes/ folder inside each framework directory: <reactDirectory>/routes/ for .tsx and .jsx files, and <svelteDirectory>/routes/ for .svelte files. Your existing pages/ folders are unchanged.

TXT
src/frontend/react/routes/
├── index.tsx                  →  /
├── about.tsx                  →  /about
├── blog/
│   ├── index.tsx              →  /blog
│   ├── [slug].tsx             →  /blog/:slug
│   ├── [slug].server.ts       →  load and beforeHandle for /blog/:slug
│   └── _components/
│       └── PostBody.tsx       →  private, not a route
└── [org]/[repo]/issues.tsx    →  /:org/:repo/issues

src/frontend/svelte/routes/
└── notes/
    ├── [id].svelte            →  /notes/:id
    └── [id].server.ts         →  load for /notes/:id

index maps to its folder's path. A [name] segment becomes an Elysia param. Files and folders that start with _ are private, so components can live next to the routes that use them. Test files (.test, .spec) are not routes.

React and Svelte routes share one URL space. Two files that claim the same path are reported when the routes are scanned.

#React Route

A React route file default-exports its page component. Like any React page, it renders the whole document.

TSX
// src/frontend/react/routes/blog/[slug].tsx
import { PostBody } from './_components/PostBody';

type PostPageProps = {
  post: { body: string; title: string };
};

const PostPage = ({ post }: PostPageProps) => (
  <html lang="en">
    <head>
      <title>{post.title}</title>
    </head>
    <body>
      <h1>{post.title}</h1>
      <PostBody body={post.body} />
    </body>
  </html>
);

export default PostPage;

The sibling [slug].server.ts can export load and beforeHandle. load returns the page's props, or a Response such as a redirect. beforeHandle runs first; a value it returns answers the request.

TS
// src/frontend/react/routes/blog/[slug].server.ts
import type { FileRouteContext } from '@absolutejs/absolute';
import { NotFound } from 'elysia';
import { findPost } from '../../../../db/posts';

export const beforeHandle = ({
  headers,
  redirect
}: FileRouteContext<'/blog/:slug'>) =>
  headers.cookie?.includes('session=') ? undefined : redirect('/login');

export const load = async ({ params }: FileRouteContext<'/blog/:slug'>) => {
  const post = await findPost(params.slug);
  if (!post) throw new NotFound();

  return { post };
};

Throwing NotFound from load renders the not-found page. Any other error renders the framework's error page.

#Svelte Route

A Svelte route is a .svelte file that reads its props with $props(). Its server module works the same way as React's.

SVELTE
<!-- src/frontend/svelte/routes/notes/[id].svelte -->
<script lang="ts">
  type Props = { note: { id: string; text: string } };

  let { note }: Props = $props();
</script>

<svelte:head>
  <title>Note {note.id}</title>
</svelte:head>

<h1>{note.text}</h1>
TS
// src/frontend/svelte/routes/notes/[id].server.ts
import type { FileRouteContext } from '@absolutejs/absolute';

export const load = ({ params }: FileRouteContext<'/notes/:id'>) => ({
  note: { id: params.id, text: `Note number ${params.id}` }
});

#Load Context

load and beforeHandle receive a FileRouteContext<Path>. Pass the route's Elysia path as the type argument.

FieldValue
paramsTyped from the path: /blog/:slug gives { slug: string }
queryQuery string values
headersRequest headers
requestThe Request
setResponse status and headers, as on an Elysia context
pathThe request path
redirect(url, status?)A redirect response. Default 302.

#Route Tree

The build scans the route folders and writes a route module, src/routes.gen.ts by default. It exports routeTree. Pass it and the manifest to fileRoutes(routeTree, manifest) after prepare().

TS
// src/backend/server.ts
import { fileRoutes, prepare } from '@absolutejs/absolute';
import { Elysia } from 'elysia';
import { routeTree } from '../routes.gen';

const { absolutejs, manifest } = await prepare();

export const server = new Elysia()
  .use(absolutejs)
  .use(fileRoutes(routeTree, manifest))
  .get('/api/health', () => 'ok');

absolute build, absolute dev and absolute typecheck write the module. Don't edit it. In absolute dev, adding, renaming or removing a route file rewrites it and the routes update without a restart.

TS
// src/routes.gen.ts (generated, do not edit)
import type { FileRouteDefinition } from '@absolutejs/absolute';
import { reactFileRoute } from '@absolutejs/absolute/react/server';
import { svelteFileRoute } from '@absolutejs/absolute/svelte/server';

export const routeTree: readonly FileRouteDefinition[] = [
  reactFileRoute<
    '/blog/:slug',
    typeof import('./frontend/react/routes/blog/[slug]'),
    typeof import('./frontend/react/routes/blog/[slug].server')
  >({
    name: 'RouteBlogSlugej2ms2',
    page: () => import('./frontend/react/routes/blog/[slug]'),
    path: '/blog/:slug',
    server: () => import('./frontend/react/routes/blog/[slug].server'),
    source: 'src/frontend/react/routes/blog/[slug].tsx'
  }),
  svelteFileRoute<
    '/notes/:id',
    typeof import('./frontend/svelte/routes/notes/[id].svelte'),
    typeof import('./frontend/svelte/routes/notes/[id].server')
  >({
    name: 'RouteNotesId6kfe7t',
    path: '/notes/:id',
    server: () => import('./frontend/svelte/routes/notes/[id].server'),
    source: 'src/frontend/svelte/routes/notes/[id].svelte'
  })
];

#Typed Props

The route module passes each route's path, page module and server module as type arguments. So load must accept the route's params and return the page's props. A page with required props must have a server module with load. The url prop is filled in by the page handler, so load doesn't return it.

TS
// [slug].server.ts returns the wrong shape:
export const load = ({ params }: FileRouteContext<'/blog/:slug'>) => ({
  article: { body: '', title: params.slug }
});

// absolute typecheck:
// src/routes.gen.ts: TS2344
//   The types returned by 'load(...)' are incompatible between these types.
//   Type '{ article: { body: string; title: string; }; }' is not assignable
//   to type 'MaybePromise<FileRouteLoadProps<PostPageProps> | Response>'.

The same check applies to Svelte routes. absolute typecheck reads the props a Svelte page declares with $props().

#Explicit Routes

An explicit route always wins over a file route for the same path. If it is registered before .use(fileRoutes(...)), the file route is skipped with a warning. If it is registered after, it replaces the file route.

TS
export const server = new Elysia()
  .use(absolutejs)
  // This explicit route answers GET /, so routes/index.tsx is not served.
  .get('/', () => handleHTMLPageRequest(asset(manifest, 'Home')))
  .use(fileRoutes(routeTree, manifest));

// Startup warning:
// File route src/frontend/react/routes/index.tsx is not served:
// an explicit route already handles GET /.