In Jeasx, a file system-based routing system is at the heart of the framework.

All server routes can be put anywhere in the src directory with filenames enclosed with brackets ([news].jsx) and should be defined as default exported functions that receive request and reply objects from Fastify as props.

Routes can be written using JSX (or MDX if installed and configured), but can also be written in JavaScript and/or TypeScript, or any other file type supported by esbuild.

A route can return various types of payloads for the client, including HTML (default), JSON, or other formats (see what a route can return). If you need to perform asynchronous operations, you can declare your route or imported components as async.

Please note: Jeasx doesn't specify any hardcoded outbase directory for esbuild, so it defaults to the lowest common ancestor directory for all your routes. So when you put all your routes into a dedicated folder (e.g. src/routes), routes will be removed from the resulting path.

Named routes

The only rule for named routes is to enclose the base filename within brackets. This convention allows you to store components, services and utilities besides your routes without exposing them as endpoints.

Route pathURL
src/[index].jsx/
src/a/b/[you-name-it].jsx/a/b/you-name-it
src/company/[index].tsx/company
src/images/[logo.svg].js/images/logo.svg
src/api/posts/[update.json].ts/api/posts/update.json
src/api/[health].json/api/health
src/api/posts/utils/format.tsThis file is not exposed as endpoint.

A route doesn't have to export a function: if the default export is a value (e.g. the object esbuild creates from [health].json), it is sent as response as is.

Code example

import { html } from "jsx-async-runtime";

// src/[hello].jsx => /hello?name=Jeasx
export default function ({ request }) {
  const name = request.query.name ?? "World";
  return (
    <>
      {html("<!DOCTYPE html>")}
      <html lang="en">
        <head>
          <title>Hello {name}</title>
        </head>
        <body>
          <h1>Hello {name}</h1>
        </body>
      </html>
    </>
  );
}

Dynamic routes

Dynamic routes are wildcards designed to capture all requests for the current folder and its subfolders. They enable the creation of content with a dynamic URL structure, such as pages retrieved from a CMS. If a named route exists in the same folder as a dynamic route, the named route takes precedence. The name for a dynamic route is fixed and must be [...path], with any file extension supported by your build (e.g. [...path].jsx, [...path].ts or [...path].mdx).

Route pathURL
src/products/[...path].jsx/products/1, /products/category/2, /products/**/*

Code example

import Layout from "../components/Layout";

// src/products/[...path].jsx
export default async function ({ request, reply }) {
  // e.g. /products/1 => "1"
  const id = request.path.split("/").at(-1);
  const product = await (await fetch(`https://dummyjson.com/product/${id}`)).json();

  if (product.message) {
    reply.status(404);
    return;
  }

  return (
    <Layout title={product.title} description={product.description}>
      <article>
        <h1>{product.title}</h1>
        <p>{product.description}</p>
      </article>
    </Layout>
  );
}

If a route returns nothing (like above after reply.status(404)), the request is passed on to the next matching route, e.g. the next [...path] or [404] route. This works for named and [index] routes, too.

404 routes

A [404] route answers all requests that no other route has answered. Like dynamic routes, [404] routes are looked up from the current folder up to the root, so you can provide a different 404 page for a section of your site. The status code is set to 404 automatically, unless your route sets another one. If no [404] route exists, Jeasx answers with an empty 404.

Route pathURL
src/blog/[404].jsxUnknown URLs below /blog, e.g. /blog/unknown
src/[404].jsxAll other unknown URLs

If you request a 404 page directly (e.g. /404 answered by src/[404].jsx or /blog/404 answered by src/blog/[404].jsx), it keeps status 200. This makes it easy to export a 404 page for a static site. If a [404] route from a parent folder answers instead, the status is 404.

Guards

Guards enable you to intercept requests and are inherited from the root to the current folder. They are valuable for controlling access to a route. Typically, a guard does not return any payload, allowing the request to be handled by the next guard or route. However, if a guard returns a response (e.g. JSX, a string or a stream), it will be delivered to the client, and no other route will be executed. A plain object is not sent as a response, but used as props (see below).

Route pathURL
src/blog/[...guard].jsx

The code of the guard is executed before everything in the current folder or below: static files, named, index, dynamic and 404 routes.

Code example

import Layout from "../components/Layout";

// src/blog/[...guard].jsx
export default function ({ request, reply }) {
  const authorization = request.headers["authorization"];
  if (authorization !== `Basic ${Buffer.from("demo:demo").toString("base64")}`) {
    reply.header("WWW-Authenticate", 'Basic realm="Restricted Area"');
    reply.status(401);
    return (
      <Layout title="Error 401">
        <h1>Error 401</h1>
        <p>You are not allowed to view this page!</p>
      </Layout>
    );
  }
}

Additionally, a guard has the capability to return an object, which will serve as props for all routes protected by the guard. This feature enables the creation of routes that are entirely independent from the request object, simplifying component testing. These objects are never sent to the client, even if no route answers the request.

export default function ({ request }) {
  const body = request.body || {};
  return { message: body["message"] };
}
export default function ({ message }) {
  return <p>{message ? message : "No message for you"}</p>;
}

Special routes like [index], [...path] or [...guard] can't be called by their names: requests like /index, /...guard or /[...guard] don't run these routes, but are handled like any other unknown URL (by a [...path] or [404] route, or answered with an empty 404). The only exception is /404 (see 404 routes). Requests with invalid URL encoding, null bytes or ./.. segments are answered with status 400.

Order of execution

For each request, Jeasx tries the possible routes in a fixed order. Guards always run first. After that, the first route which answers wins. For a request to /a/b/c, the order is:

  1. Guards from the root to the current folder: /[...guard], /a/[...guard], /a/b/[...guard], /a/b/c/[...guard]
  2. A static file from public or dist (see CSS & JavaScript)
  3. The named route /a/b/[c]
  4. The index route /a/b/c/[index]
  5. Dynamic routes from the current folder to the root: /a/b/c/[...path], /a/b/[...path], /a/[...path], /[...path]
  6. 404 routes from the current folder to the root: /a/b/c/[404], /a/b/[404], /a/[404], /[404]

So a static file wins over a named route with the same path, and src/a/b/[c].jsx wins over src/a/b/c/[index].jsx.

What is the difference between request.url, request.path and request.route?

The vanilla Fastify request object exposes the current URL (e.g. /path/to/route?foo=bar) via request.url.

Jeasx adds two additional attributes to the Fastify request object to improve the developer experience:

  • request.path gives you the URL-decoded path without any query parameters (e.g. /path/to/route). Backslashes become slashes and repeated slashes are collapsed, so don't decode it again with decodeURIComponent. Use request.url if you need the raw path.
  • request.route provides the path to the current endpoint handler (e.g. /path/to/[route])