# 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 [#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`:

```ts title="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]`:

```ts
"/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`:

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

### ApiRoute

| Prop            | Type                                                                                 | Description                                                                                                                                                   |
| --------------- | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `path`          | `string`                                                                             | The path without the base path. `[name]` matches text without `/`, and `[...name]` matches the rest.                                                          |
| `staticParams?` | `StaticParams<string> \| undefined`                                                  | The values of the params of a `static` route by name, one generated file each.                                                                                |
| `page?`         | `((params: Record<string, string \| string[]>) => string \| undefined) \| undefined` | The path of the page the route is made from at `params`, so middleware guards both with one check. Without `render`, the route renders the way its page does. |
| `render?`       | `RenderMode \| undefined`                                                            | A `static` route is generated from its `GET` handler. Default: ``"dynamic", or as its `page` renders``                                                        |
| `ALL?`          | `ApiHandler<string> \| undefined`                                                    | Handles the methods that have no handler.                                                                                                                     |
| `GET?`          | `ApiHandler<string> \| undefined`                                                    |                                                                                                                                                               |
| `POST?`         | `ApiHandler<string> \| undefined`                                                    |                                                                                                                                                               |
| `PUT?`          | `ApiHandler<string> \| undefined`                                                    |                                                                                                                                                               |
| `PATCH?`        | `ApiHandler<string> \| undefined`                                                    |                                                                                                                                                               |
| `DELETE?`       | `ApiHandler<string> \| undefined`                                                    |                                                                                                                                                               |
| `HEAD?`         | `ApiHandler<string> \| undefined`                                                    |                                                                                                                                                               |
| `OPTIONS?`      | `ApiHandler<string> \| undefined`                                                    |                                                                                                                                                               |

## Static Routes [#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`:

```ts
createApi({
  path: "/api/pages/[...slugs]",
  render: "static", // [!code highlight]
  // The value of `[...slugs]` is a list of segments.
  staticParams: () => this.getPages().map((page) => ({ slugs: page.slugs })), // [!code highlight]
  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 [#data-routes]

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

```ts tab="vuesho.config.ts"
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();
      },
    });
  },
});
```

```vue tab="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>
```

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](/content-hooks#page-data)'s `dataRoutes`, navigating to the page loads the value first.

<Callout type="warn" title="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.
</Callout>

## Derived Routes [#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:

```ts title="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), // [!code highlight]
      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:

### PageRoute

| Prop       | Type                                                                                                                                                                                        | Description                                                                             |
| ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------- |
| `path`     | `string`                                                                                                                                                                                    | The pattern, with the language prefix and without the base path.                        |
| `lang`     | `string`                                                                                                                                                                                    | The route's language.                                                                   |
| `render`   | `RenderMode`                                                                                                                                                                                | Whether the build generates the route, or a server renders it on request.               |
| `pages`    | `readonly { readonly path: string; readonly params: Readonly<Record<string, string \| string[]>>; readonly translations: readonly { readonly lang: string; readonly path: string; }[]; }[]` | The pages it lists: its path when it has no params, or a page per `staticParams` entry. |
| `data`     | `Readonly<Partial<PageData>>`                                                                                                                                                               | The page data before the route's `data` function and `transformPage`.                   |
| `markdown` | `boolean`                                                                                                                                                                                   | Whether its pages have Markdown.                                                        |

## Middleware [#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:

```ts title="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](/deploying#content-security-policy). A rewrite with `next(path)` only affects requests that reach the server. A link in the app still navigates to the URL as written.

<Callout type="warn" title="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](/dynamic-rendering#protected-pages) shows. To vary a generated file by a request header, use [content negotiation](/plugin-api#content-negotiation).
</Callout>

## Platform Context [#platform-context]

On a server, the request is a `ServerRequest` from [srvx](https://srvx.h3.dev). 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:

```ts
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 [#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:

```ts title="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](/plugin-api#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`:

```ts tab="src/releases/theme.ts"
import type { PluginTheme } from "vuesho/client";
import type { ReleasesProps } from "./plugin";

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

```vue tab="src/releases/Releases.vue"
<script setup lang="ts">
import { Link, type ViewPageOf } from "vuesho/client";
import { HomeShell } from "vuesho/theme";
import type { ReleasesProps } from "./plugin";

defineProps<{ page: ViewPageOf<{ releases: ReleasesProps }, "releases"> }>();
</script>

<template>
  <HomeShell>
    <h1 class="mb-6 text-2xl font-semibold">{{ page.pageData.title }}</h1>
    <Link v-for="release in page.props.releases" :key="release.url" :href="release.url">
      {{ release.title }}
    </Link>
  </HomeShell>
</template>
```

Props reach the browser as JSON, so `ViewPageOf` types a `Date` as a string. A site replaces the component in its [theme](/theme#views-and-page-bodies)'s `views`, or replaces the whole page with a [custom page](/custom-pages) 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`:

```ts
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:

```ts tab="Plugin"
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]] : [])),
    ),
});
```

```vue tab="News.vue"
<template>
  <article v-for="url in page.props.urls" :key="url" class="prose">
    <component :is="page.contentOf[url]" />
  </article>
</template>
```

### ViewRoute

| Prop            | Type                                                                                                                                   | Description                                                                                                                                                |
| --------------- | -------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `path`          | `string`                                                                                                                               | The path without the base path or the language prefix. The site adds the prefix unless `lang` is `false`.                                                  |
| `view`          | `(env: PageRouteEnv<string, string>) => Awaitable<undefined>`                                                                          | Returns the page at `params` in `lang`, or none for a 404.                                                                                                 |
| `render?`       | `RenderMode \| undefined`                                                                                                              | Whether the build generates the route, or a server renders it on request. Default: ``"static" without params or with `staticParams`, "dynamic" otherwise`` |
| `staticParams?` | `StaticParams<string> \| undefined`                                                                                                    | The values of the params of the pages generated at build time, like `{ path: ["a", "b"] }` for `[...path]`.                                                |
| `data?`         | `Partial<PageData> \| ((env: PageRouteEnv<string, string>) => Awaitable<Partial<PageData> \| undefined>) \| undefined`                 | The page data for its pages, or a function of the page. `undefined` makes it a 404.                                                                        |
| `markdown?`     | `((env: PageRouteEnv<string, string>) => Awaitable<string>) \| undefined`                                                              | A page's text as Markdown, without its title and description.                                                                                              |
| `contentOf?`    | `((env: PageRouteEnv<string, string>) => Awaitable<Readonly<Record<string, Page<string \| undefined, SourcePageData>>>>) \| undefined` | The content pages whose content a page shows, under keys you choose, each a component in `page.contentOf`.                                                 |
| `lang?`         | `string \| false \| undefined`                                                                                                         |                                                                                                                                                            |
