Skip to Content
Vuesho

Routes

Add API routes, data for your components, and middleware.

The routes hook of a plugin adds API routes with createApi() and data routes with createDataRoute(). It runs once, when the site starts:

vuesho.config.ts
createSite(docs.toFumadocsSource()).plugins({
  name: "site:api",
  routes({ createApi }) {
    createApi({
      path: "/api/pages",
      GET: () => Response.json(this.getPages().map((page) => page.url)),
    });
  },
});

A handler takes a standard Request and returns a Response. Routes match before pages. The most specific route that matches the URL and handles the method answers, so a route for POST only doesn't hide a page or another route at the same path.

API Routes

Path Params

[name] in a path matches text without /, and [...name] matches the rest of the path. Text can surround a param, like in /data/[id].json or /[...path].md, and a path can have several params. The handler receives their decoded values in params:

createApi({
  path: "/api/files/[...path]",
  GET: (_request, { params }) => Response.json({ path: params.path }), // "a/b" for /api/files/a/b
});

A rest param is the last param of the path, and two params need text between them, like /[pkg]-v[version]: a param takes the shortest text after which the rest of the path matches, so /react-dom-v19 gives pkg: "react-dom" and version: "19". A path that breaks these rules fails when the site starts, naming the route.

When several routes match a URL, the most specific one answers. The segments are compared in order: a fixed segment wins over text with a param, which wins over a param alone, then text with a rest param, then a rest param alone. So /api/special answers /api/special before /api/[name], in any order of creation.

A path has no base path. It has no language prefix either: to add a route per language, call createApi() for each of this.languages, with this.localizePath(lang, path) as its path.

Methods

A route has a handler per HTTP method: GET, POST, PUT, PATCH, DELETE, HEAD and OPTIONS. HEAD falls back to GET, and ALL handles every method without its own handler:

createApi({
  path: "/api/feedback",
  POST: async (request) => {
    const body = await request.json();
    return Response.json({ received: body });
  },
  ALL: () => new Response("Use POST", { status: 405 }),
});

A request with a method that the route doesn't handle gets a 405 response.

Static Routes

An API route renders on demand by default. With render: "static", the build generates it from its GET handler, so a static host can serve it as a file:

createApi({
  path: "/version.json",
  render: "static",
  GET: () => Response.json({ version: "1.0.0" }),
});

A static route with a param generates one file per entry of staticPaths: a string for [name], a list of segments for [...name]. staticPaths can be a function, sync or async. A static route with a param and without staticPaths stops the site from starting, with an error that names the route: list its paths, or set render: "dynamic" to answer requests on a server. An empty list is allowed, and generates no file. A route with render: "dynamic" takes no staticPaths, and stops the site from starting with one.

With several params, an entry is an object of their values by name:

createApi({
  path: "/packages/[pkg]-v[version].json",
  render: "static",
  staticPaths: [
    { pkg: "vue", version: "3" },
    { pkg: "vite", version: "8" },
  ],
  GET: (_request, { params }) => Response.json(params), // { pkg: "vue", version: "3" }
});

An entry without a value for a param, with a key that isn't a param, or with a value the path can't read back, like a / in a value of [name], fails with an error that names the route and the entry.

createApi({
  path: "/api/pages/[...slugs]",
  render: "static",
  staticPaths: () => this.getPages().map((page) => page.slugs),
  GET: async (_request, { params }) => {
    const page = this.getPage(`/${params.slugs}`);
    if (!page) return new Response("Not Found", { status: 404 });
    return Response.json(await this.getPageData(page));
  },
});

A static route never runs on demand: on the dev server and on a server deployment, it answers only the paths it lists, like the files of the build.

Following the Content

A route that lists your pages is generated at build time while every page it lists is. Once a page renders on demand, because its source is dynamic or a route rule excludes it, the route renders on demand too. this.getContentRender() gives that render mode, for every source or for one by its key:

createApi({
  path: "/pages.json",
  render: this.getContentRender(),
  GET: () => Response.json(this.getPages().map((page) => page.url)),
});

The sitemap, llms.txt and the search index use this, so they follow your pages without config. A route made from each page, like a Markdown copy at <page>.md, follows that page instead: list a page in staticPaths only when this.getPageRender(page.url) is "static", and add a route with render: "dynamic" at the same path for the pages that render on demand, as in Derived Routes.

Data Routes

A data route is a value that your components read. createDataRoute() adds one, and its GET response is the JSON of what load returns, with undefined as a 404:

vuesho.config.ts
createSite(docs.toFumadocsSource()).plugins({
  name: "site:contributors",
  routes({ createDataRoute }) {
    createDataRoute({
      path: "/api/contributors.json",
      load: async () => {
        const response = await fetch("https://api.github.com/repos/vuejs/core/contributors");
        return response.json();
      },
    });
  },
});

A component reads it with useDataRoute(path) of vuesho/client, which returns a ref of the value. The ref is undefined until the value is read, and when the route has no value at path:

src/components/Contributors.vue
<script setup lang="ts">
import { useDataRoute } from "vuesho/client";

const contributors = useDataRoute<{ login: string }[]>("/api/contributors.json");
</script>

<template>
  <ul v-if="contributors">
    <li v-for="user in contributors" :key="user.login">{{ user.login }}</li>
  </ul>
</template>

How the value reaches the component:

  • On the server, useDataRoute() calls the load function of the route before the component renders, with the request of the page in its env when the route renders on demand. A static data route never receives it, on the dev server too. The HTML has the value, and the value comes with the page, so the browser hydrates it without fetching it.
  • In the browser, a component on a page you navigated to fetches the route once it is mounted, and the ref is set when the value arrives. The app keeps the value, and the load function of the route receives the request of that fetch. A request that fails, like without a network, is reported in the console and made again the next time.

The path can be a ref or a getter, and the ref follows it when it changes:

const user = useDataRoute(() => `/api/users/${props.name}.json`);

The browser fetches data routes, so a data route is generated at build time by default. A data route with params needs staticPaths or render: "dynamic", and a data route that reads your content sets render: this.getContentRender(). With render: "dynamic", it needs a server deployment.

An error that load throws on the server fails the page, like an error of its render.

The value of a data route is public: it is written into the HTML of the pages that read it, and the server calls the load function directly for a page, so middleware runs for the page but not for the data route. For data that depends on who asks, write an API route with a GET handler and fetch it in the browser.

Shared Data

A data route with shared: true has the same value on every page. Its value isn't sent with each page: the page preloads the route, the browser fetches it once for every page, and the app has it before the page hydrates.

createDataRoute({
  path: "/api/announcement.json",
  shared: true,
  load: () => ({ text: "Version 2 is out" }),
});

Derived Routes

The deriveRoutes hook adds routes made from the page routes of the site, once every plugin has created its own in routes. It runs once per language, with the final list of that language in routes: the views of plugins, the custom pages and the not found page. This one adds a printable copy of every page of a route:

vuesho.config.ts
import type { ApiHandler } from "vuesho/config";

createSite(docs.toFumadocsSource()).plugins({
  name: "site:print",
  deriveRoutes({ createApi }, { lang, routes }) {
    const path = `${this.localizePath(lang, "/print")}/[...path]`;
    const GET: ApiHandler = (_request, { params }) => new Response(`Print of /${params.path}`);
    const pages = routes.flatMap((route) => route.pages.map((page) => page.path));
    const generated = pages.filter((page) => this.getPageRender(page) === "static");
    // the copies of the pages the build generates are files too
    createApi({
      path,
      render: "static",
      staticPaths: generated.map((page) => page.split("/").filter(Boolean)),
      GET,
    });
    // the copy of a page that renders on demand renders on demand too
    if (generated.length < pages.length || routes.some((route) => route.render === "dynamic")) {
      createApi({ path, GET });
    }
  },
});

The static route answers the paths it lists, and the route on demand answers the others.

A route has its path with the language prefix, its lang and render, the pages it lists with their params and translations, and its data, the page data of its pages. createView() in deriveRoutes adds a view in the language of the call. this.getPageRoutes() returns the same list, with the routes deriveRoutes added, from a handler or a hook that runs on a request. It throws in routes, where plugins are still creating them.

Middleware

The middleware hook runs first on every request the server receives, before routes and pages. Call next() to continue, and change the response it returns:

vuesho.config.ts
createSite(docs.toFumadocsSource()).plugins({
  name: "site:headers",
  async middleware(_request, next) {
    const response = await next();
    const out = new Response(response.body, response);
    out.headers.set("x-powered-by", "vuesho");
    return out;
  },
});

next(path) serves another path instead, without a redirect. The path has no base path, and can have a query:

async middleware(request, next) {
  const { pathname } = new URL(request.url);
  return next(pathname === "/latest" ? "/guide/install" : undefined);
}

The third argument has page, the path of the page a request is for: the path of the request, or for the data the browser loads for a page, the path of that page. A check of a section of the site reads page, so it guards the page and its data together.

Middleware of several plugins runs in plugin order, and each next() calls the next plugin. A request sees a path in its one form: a GET of another spelling of it, like /guide/install/, redirects to /guide/install before any middleware runs.

A page served at another URL with next(path) renders when the server receives the request for that URL. A link to it inside the site loads the content of the URL itself, so rewrite pages that readers enter the site by, like /latest, and link to their real path.

Requests that the host serves from the files of the build, like pages generated at build time, never reach middleware. A middleware that must see every request needs the pages to render on demand, on a server deployment, which a route rule with prerender: false sets for any path, see Session Checks. The compiled Markdown of a page in your collections stays a file of the build even then, so a middleware guards the HTML and the data of the page, not that file.