Skip to Content
Vuesho

Routes

Routes, middleware and views from plugins.

A plugin adds API routes, data routes and views in its routes hook, and handles requests in middleware. Paths never include the base path, and the site adds the language prefix to a view's path only.

API Routes

An API route has one handler per HTTP method. ALL handles every method that has no handler, HEAD falls back to GET, and other methods get a 405:

vuesho.config.ts
createSite(docs.toSource()).plugins({
  name: "acme:feedback",
  routes({ createApi }) {
    createApi({
      path: "/api/feedback/[page]",
      POST: async (request, { params }) => {
        const body = await request.json();
        return Response.json({ page: params.page, received: body });
      },
    });
  },
});

A route answers only its own methods, so a POST route doesn't hide a page at the same path. When several patterns match a path, the most specific one wins, so /api/special beats /api/[name], which beats /api/[...rest]:

"/api/users/[name]"; // /api/users/fuma gives { name: "fuma" }
"/api/files/[...path]"; // /api/files/a/b gives { path: ["a", "b"] }, and /api/files gives { path: [] }
"/data/[id].json"; // /data/42.json gives { id: "42" }
"/[pkg]-v[version]"; // /react-dom-v19 gives { pkg: "react-dom", version: "19" }

params is typed from the literal parts of the path, so params.path above is a string[].

For a route in each language, loop over this.languages:

for (const lang of this.languages) {
  createApi({
    path: this.localizePath(lang, "/api/pages"),
    GET: () => Response.json(this.getPages(lang).map((page) => page.url)),
  });
}

Prop

Type

Static Routes

API routes render on request by default, so they need a server. With render: "static", the build writes the GET response to a file. A static route with params lists their values in staticParams:

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

A static route answers only the paths it lists, in development too. render: this.getContentRender() makes a route static when the content is static, and dynamic when a source renders on request. this.getContentRender("docs") checks the docs source only.

Data Routes

A data route serves JSON that a component reads with useDataRoute(). The server loads the value while rendering the page, so the first render already has it:

createSite(docs.toSource()).plugins({
  name: "acme: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();
      },
    });
  },
});

Data routes are static by default, so one with params needs staticParams or render: "dynamic".

shared: true marks a value that is the same on every page, so the browser fetches it once instead of reading it from each page's HTML. When a page lists the route in its page data's dataRoutes, navigating to the page loads the value first.

Data Routes Are Public

The value is written into the page's HTML, and the server loads it without running middleware. Serve private data from an API route that the browser fetches.

Derived Routes

deriveRoutes runs once per language, after every plugin's routes hook. It receives the language's page routes: the views, the custom pages and the not found page. A plugin creates routes from them and from the content pages, like a .txt copy of every page:

vuesho.config.ts
createSite(docs.toSource()).plugins({
  name: "acme:print",
  deriveRoutes({ createApi }, { lang, routes }) {
    // A page URL has the language's prefix, like `/ja/guide`, which the route's path adds again.
    const home = this.localizePath(lang, "/");
    const toParam = (url: string) =>
      url === home ? ["index"] : url.slice(home === "/" ? 1 : home.length + 1).split("/");
    const toUrl = (param: string[]) => {
      const path = param.join("/");
      return this.localizePath(lang, path === "index" ? "/" : `/${path}`);
    };

    const urls = [
      ...this.getPages(lang).map((page) => page.url),
      ...routes
        .filter((route) => route.markdown)
        .flatMap((route) => route.pages.map((page) => page.path)),
    ];
    createApi({
      path: `${this.localizePath(lang, "/print")}/[...path].txt`,
      // The page this route is made from.
      page: (params) => toUrl(params.path), 
      staticParams: urls.map((url) => ({ path: toParam(url) })),
      GET: async (_request, { params }) =>
        new Response(await this.getPageMarkdown(toUrl(params.path))),
    });
  },
});

page names the page a route is made from, so the route renders like its page, passes through the middleware that guards it, and responds with a 404 when the page is missing.

Each entry in routes is a page route:

Prop

Type

Middleware

middleware runs on every request to the server, before the routes and the pages, in plugin order. varies lists the request headers that responses depend on, so caches keep one response per value:

vuesho.config.ts
createSite(docs.toSource()).plugins({
  name: "acme:guard",
  middleware: {
    async handle(request, next, { page }) {
      // Serves another path, without a redirect.
      if (new URL(request.url).pathname === "/latest") return next("/guide/install");
      // `page` is the request's page, also for its data route and its Markdown.
      if (page.startsWith("/internal/") && !request.headers.get("cookie")?.includes("session=")) {
        return new Response("Unauthorized", { status: 401 });
      }
      const response = await next();
      const out = new Response(response.body, response);
      out.headers.set("x-powered-by", "vuesho");
      return out;
    },
  },
});

next(new Request(request, { headers })) continues with a changed request, like one that carries a CSP nonce. A rewrite with next(path) only affects requests that reach the server. A link in the app still navigates to the URL as written.

Files Skip Middleware

A static host, or a server that serves a generated file, runs no middleware, so a guarded page must render on request, as Protected Pages shows. To vary a generated file by a request header, use content negotiation.

Platform Context

On a server, the request is a ServerRequest from srvx. It carries the client's address and the platform's context. Pages and routes that the build generates have neither. Install srvx for the type:

import type { ServerRequest } from "srvx";

createApi({
  path: "/api/feedback",
  POST: async (request: ServerRequest) => {
    console.log(request.ip); // The client's address.
    // The platform's context, like Cloudflare's `env`.
    const webhook = request.runtime?.cloudflare?.env.FEEDBACK_WEBHOOK;
    if (typeof webhook === "string") {
      // Work that continues after the response, where the platform supports it.
      request.waitUntil?.(fetch(webhook, { method: "POST", body: await request.text() }));
    }
    return new Response(null, { status: 204 });
  },
});

Views

A view is a page that a plugin creates and its theme renders, like a blog's index. Its view function returns a component name and props, which Plugin<C, { views }> types:

src/releases/plugin.ts
import type { AppShape, Plugin } from "vuesho/config";

export interface ReleasesProps {
  releases: { title: string; url: string }[];
}

export function releasesPlugin<C extends AppShape>(): Plugin<
  C,
  { views: { releases: ReleasesProps } }
> {
  return {
    name: "acme:releases",
    theme: "/src/releases/theme.ts",
    routes({ createView }) {
      createView({
        path: "/releases",
        data: { title: "Releases" },
        view: ({ lang }) => ({
          type: "releases",
          props: {
            releases: this.getPages(lang).map((page) => ({
              title: page.data.title ?? page.url,
              url: page.url,
            })),
          },
        }),
      });
    },
  };
}

The plugin's theme module maps each view to a component. The component receives page, with the props in page.props and the page data in page.pageData:

import type { PluginTheme } from "vuesho/client";
import type { ReleasesProps } from "./plugin";

export default {
  views: { releases: () => import("./Releases.vue") },
} satisfies PluginTheme<{ views: { releases: ReleasesProps } }>;

Props reach the browser as JSON, so ViewPageOf types a Date as a string. A site replaces the component in its theme's views, or replaces the whole page with a custom page at the same path. A view can't share a URL with a content page.

A view with params takes the same options as a custom page. When view or data returns undefined, the page is a 404:

const posts: Record<string, string> = { hello: "Hello", bye: "Bye" };

createView({
  path: "/blog/[slug]",
  // The pages the build generates. Without it, a view with params renders on request.
  staticParams: Object.keys(posts).map((slug) => ({ slug })),
  // The page data: title, description and head tags.
  data: ({ params }) => (posts[params.slug] ? { title: posts[params.slug] } : undefined),
  view: ({ params }) =>
    posts[params.slug] ? { type: "post", props: { title: posts[params.slug] } } : undefined,
  // The text of `<page>.md`, under the title and description from `data`.
  markdown: ({ params }) => `The post "${posts[params.slug]}".`,
  // One language, or `false` for the path as written. By default, the view exists in every language.
  lang: "en",
});

With render: "dynamic", a view renders on request, and view, data and contentOf receive the request. contentOf returns an object of the content pages whose bodies the view renders, with keys of your choice:

createView({
  path: "/news",
  render: this.getContentRender("news"),
  data: { title: "News" },
  view: ({ lang }) => ({
    type: "news",
    props: {
      urls: this.getPages(lang).flatMap((page) => (page.type === "news" ? [page.url] : [])),
    },
  }),
  contentOf: ({ lang }) =>
    Object.fromEntries(
      this.getPages(lang).flatMap((page) => (page.type === "news" ? [[page.url, page]] : [])),
    ),
});

Prop

Type