Redirects

Let editors send old URLs to new ones with @cms/redirects, and look them up from your website.

@cms/redirects is a plugin for redirects editors manage themselves: an old path, where it goes now, and the status code. It adds:

  • a Redirects collection in the admin
  • a public resolve route your website asks for the redirect of a path
  • an import page that creates redirects from a CSV file, when importPage is on
          pnpm add @cms/redirects
        
          // cms.config.tsx
import { config } from "@cms/config";
import { redirects } from "@cms/redirects";

export default config({
  // ...
  plugins: [redirects()],
});
        

Run cms migration generate, then cms migration apply, to create the table.

Options

Option Type Description
entity string The collection’s name. Default: "redirects". Change it when the project already has an entity by that name.
importPage boolean Adds the Import redirects page to the admin. Default: false. The import route is mounted either way.
roles string[] Roles, beyond admins, that may open the import page and import a file. Default: [].
name string The instance name, which the routes and page mount under. Default: "redirects".
          plugins: [redirects({ entity: "url-redirects", importPage: true, roles: ["seo"] })],
        

The plugin adds the collection but no permissions on it: grant roles read, create, update and delete on it in their permissions, as for your own entities. Your website doesn’t need any, since the resolve route is public.

With a custom admin.sidebar, place the plugin with plugin("redirects"); see Plugins → Admin pages and sidebar.

The collection

Field Description
from The old path, like /pages/about-1. Unique. Saved lowercase without a trailing slash, which is also how requests are matched, so /About/ and /about are one redirect. Characters a browser percent-encodes are saved encoded, the way requests arrive: /old page becomes /old%20page. A ? or # is rejected: matching reads the path only, and the request’s query string is carried over.
to Where it goes: a path on this site (/about) or a full http:// or https:// URL. Stored as written.
status 301 (permanent, the default), 302 (temporary), 307 or 308 (the same, keeping a form’s method).
note Why the redirect exists. Not shown on the site.

Redirects aren’t versioned: one is live as soon as it’s saved. Saving a redirect whose to is its own from fails, since following it would loop.

Looking up a redirect

GET /api/plugins/redirects/resolve?path=<path> answers anyone, with no API key or public role needed:

          { "data": { "to": "/about?utm_source=mail", "status": 301 } }
        

path can carry the request’s query string, which is added to to (a query to already has wins on a clash). A path with no redirect gets 404.

Ask only once your own routes found nothing, so a redirect can never hide a live page, and a page that works never pays for the lookup:

          // src/lib/redirects.ts
import { ClientError } from "@cms/client";
import { cms } from "./cms";

export async function findRedirect(path: string) {
  try {
    const { data } = await cms.request<{ data: { to: string; status: number } }>(
      "/plugins/redirects/resolve",
      { params: { path } },
    );
    return data;
  } catch (error) {
    if (error instanceof ClientError && error.status === 404) return null;
    throw error;
  }
}
        
          // In the catch-all route, after no page matched (TanStack Router shown)
const moved = await findRedirect(`${location.pathname}${location.searchStr}`);
if (moved) throw redirect({ href: moved.to, statusCode: moved.status });
throw notFound();
        

Each lookup is one indexed query. For a busy site, cache the answers, 404s included, in your website or a CDN in front of the CMS for a few minutes: an edited redirect then reaches the site once that cache expires.

URL patterns

The plugin matches exact paths only, with no wildcards. A whole family of old URLs, like every /products/<handle> moving to /product/<handle>, belongs in your website’s code, checked after the CMS’s exact redirects: that’s structure, not content, and one deleted row shouldn’t break thousands of URLs.

          const product = /^\/products\/([^/]+)$/.exec(location.pathname);
const moved =
  (await findRedirect(`${location.pathname}${location.searchStr}`)) ??
  (product ? { to: `/product/${product[1]}`, status: 301 } : null);
        

Leaving a redirect when a page is deleted

When a document has a path (a path() field from @cms/paths, or any slug field holding a value that starts with /), its delete dialog offers Leave a redirect. Checked, it creates a 301 from the document’s path once the delete commits. The destination starts as the path of the replacement picked in the same dialog, and the editor can type another path or a full URL.

The redirect is saved after the delete, as the editor, so their permissions on the redirects collection apply. If it can’t be saved, the document stays deleted and the dialog’s toast says why; add the redirect by hand in the collection.

Importing a CSV

Turn the page on with importPage: true while the project imports, usually when a site moves to the CMS, and off again once it’s done. The Import redirects page creates redirects from a file with the columns from, to, status and note. status (default 301) and note are optional, a header row starting with from is skipped, and a file whose first line has tabs and no commas is read as tab-separated.

          from,to,status,note
/pages/about-1,/about,301,Old Shopify page
/blogs/news,/blog,,
/old-shop,https://shop.example.com,302,
        

Before anything is saved, the page shows every row and flags those it can already tell are wrong: a missing or malformed from or to, an unknown status, a redirect to itself, a from that repeats in the file, and chains, where one row’s to is another row’s from (two hops for the visitor). Nothing is imported until every row passes, so fix the file and choose it again.

The import then saves each row on its own, as the editor, so their permissions apply. A row whose from already exists fails as “already exists” and the existing redirect is left as it is; to change one, edit or delete it and import the row again. The page lists what happened to each row.

The page sends the whole file in one request, to POST /api/plugins/redirects/import with { rows: [{ from, to, status, note }] }, so a large file isn’t stopped by the rate limit. Scripts can call it too, with an API key whose role may open the page, or create redirects one by one through the REST API.

Moving an existing redirects collection to the plugin

A project with its own redirects entity, with the fields from, to, status and an optional note and no versions, can switch without a schema change: remove its entity and register the plugin under the same name.

          plugins: [redirects({ entity: "redirect" })],
        

Run cms migration generate to confirm the migration is empty. Rows stored with uppercase letters or a trailing slash in from won’t match until they’re saved again.

Previous

Paths

Next

Shopify