klnap

payload redirect

by klnap
Redirects & URLs
v3
>=3.94.1 <4
MIT

Overview

Summary generated from the README

Adds a redirects collection to Payload for manual 301 and 302 rules. It can also create permanent redirects automatically when a draft-enabled collection or global changes its published path. Rules are validated for unique sources and redirect cycles. The plugin only stores rules; the application must match requests and send responses. Atomic graph writes require PostgreSQL.

Features

  • Manual 301 and 302 rules managed in the Payload admin
  • Automatic 301 rules created on published path changes
  • Path templates, per-locale paths, or custom path resolver functions
  • Locale prefixes and support for Payload localization
  • Unique normalized sources and cycle detection on every write
  • Overrides for the generated collection and its access rules

Use cases

  • Preserve old URLs when editors change a slug or category on a published page
  • Create temporary campaign links that redirect to another path
  • Feed a Next.js proxy with redirect rules looked up from Payload

From the author

Redirect management for Payload CMS.

Installation

npm i @klnap/payload-redirect

0

Stars

0

Forks

0

Open Issues

Yesterday

Last Updated

3.4k

Weekly Downloads

v0.4.19

npm Version

209.6 KB

Unpacked Size

0

Dependencies

GitHub stars

00 since Nov 22

Show data
GitHub stars by day (UTC)
DateStars
Dec 6, 20260
Dec 5, 20260
Dec 4, 20260
Dec 3, 20260
Dec 2, 20260
Dec 1, 20260
Nov 30, 20260
Nov 29, 20260
Nov 28, 20260
Nov 27, 20260
Nov 26, 20260
Nov 25, 20260
Nov 24, 20260
Nov 23, 20260
Nov 22, 20260
npm weekly downloads

3.4K+3.4K since Nov 26

Show data
npm weekly downloads by day (UTC)
DateWeekly downloads
Dec 6, 20263,378
Dec 5, 20263,492
Dec 4, 20263,544
Dec 3, 20263,193
Dec 2, 20263,123
Dec 1, 20262,959
Nov 30, 20261,253
Nov 29, 2026757
Nov 28, 2026542
Nov 27, 20260
Nov 26, 20260

Each point is npm's rolling 7-day download count.

Health Score

79/100Excellent

Composite score based on GitHub activity, stars, npm downloads, publish recency, dependency count, and package size.

Badge for your README

Payload Directory health badge
Markdown
[![Payload Directory](https://payloaddirectory.dev/badge/1472041920-root.svg)](https://payloaddirectory.dev/plugins/1472041920-root)
HTML
<a href="https://payloaddirectory.dev/plugins/1472041920-root"><img src="https://payloaddirectory.dev/badge/1472041920-root.svg" alt="Payload Directory"></a>
Updated Dec 4, 2026Created Nov 25, 2026Published Dec 4, 2026

README

@klnap/payload-redirect

Automatic and manual redirects for Payload CMS. Tracks published path changes across Collections and Globals and stores redirect rules using native Payload collections.

Features

  • Automatically manages permanent 301 redirects for published path changes when prior publication history is available, while preserving manual rules.
  • Provides a Payload Admin collection for manual 301 and temporary 302 rules.
  • Supports Payload localization, query-specific sources, destination fragments, and custom path resolvers.
  • Protects manual rules, enforces normalized source uniqueness, and validates redirect cycles.
  • Uses PostgreSQL transactions and transaction-scoped coordination for atomic, concurrent graph writes.
  • Has zero runtime dependencies.

Installation

bun add @klnap/payload-redirect
# or
npm install @klnap/payload-redirect

Payload is a peer dependency; install @payloadcms/db-postgres when using PostgreSQL.

Usage

Register redirects() once in payload.config.ts. Manual rules are then available in the Payload Admin without automatic path configuration:

import { redirects } from "@klnap/payload-redirect";
import { buildConfig } from "payload";

export default buildConfig({
  // database, collections, and other Payload options
  plugins: [redirects()],
});
FromToStatusUse
/old-guide/guides/start#installation301Permanent page move
/summer/offers?utm_source=sms302Temporary campaign link

For automatic rules, configure a draft-enabled Collection or Global. This Collection-local option tracks the complete path, including category changes:

import type { CollectionConfig } from "payload";
import type { RedirectCollectionOptions } from "@klnap/payload-redirect";

const Articles: CollectionConfig = {
  slug: "articles",
  versions: { drafts: true },
  fields: [
    { name: "slug", type: "text", required: true },
    { name: "category", type: "text", required: true },
  ],
  custom: {
    redirect: {
      path: "/articles/[category]/[slug]",
    } satisfies RedirectCollectionOptions<"articles">,
  },
};

Configure a Global the same way with GlobalConfig:

import type { GlobalConfig } from "payload";
import type { RedirectGlobalOptions } from "@klnap/payload-redirect";

const About: GlobalConfig = {
  slug: "about",
  versions: { drafts: true },
  fields: [{ name: "slug", type: "text" }],
  custom: { redirect: { path: "/[slug]" } satisfies RedirectGlobalOptions<"about"> },
};

Alternatively, configure Collections and Globals centrally; a central entry replaces that entity's custom.redirect:

plugins: [redirects({
  collections: { articles: { path: "/articles/[slug]" } },
  globals: { about: { path: "/[slug]" } },
})],

Enable Payload localization, localize the route fields, and use paths for locale-specific templates. Both paths and any localePrefixes must cover every configured locale:

redirects({
  localePrefixes: { en: "", fr: "/fr" },
  collections: {
    articles: {
      paths: {
        en: "/articles/[slug]",
        fr: "/articles/[slug]",
      },
    },
  },
});

Payload fallback values are not used to invent a missing locale path. See configuration options for path, paths, and getPath.

Configuration

OptionDescription
collections, globalsAutomatic path configuration by entity slug. Choose one of path, paths, or getPath.
localePrefixesOptional per-locale prefixes for templates.
overridesCustomize the generated redirects collection.

path is a template such as /articles/[slug]; paths maps locale codes to templates; getPath resolves a path from the document and locale. Central configuration takes precedence over custom.redirect.

Customize the generated redirects collection using overrides. This follows Payload plugin conventions; overrides is not a native CollectionConfig property.

redirects({
  overrides: {
    slug: "url-redirects",
    fields: ({ defaultFields }) => [...defaultFields, { name: "note", type: "textarea" }],
  },
});

The collection uses Payload access control; anonymous access is disabled by default. Keep lookups server-side unless public reads are required.

Published transitions compare the prior published path with the new published path. First publication, draft saves, unchanged republication, unpublishing, and deletion create no automatic rule. If a source is already occupied by a manual rule, the plugin leaves it unchanged and skips automatic creation; graph conflicts such as cycles are rejected without reclaiming historical rules. Editing or disabling an automatic rule makes it manual; later publication does not overwrite that editorial choice. Generated redirects share the content transaction; on PostgreSQL, rejected graph validation rolls back the publication. Graph writes require an active PostgreSQL transaction at READ COMMITTED; other adapters do not have the same verified concurrency guarantee.

Normalized source paths are globally unique, including disabled rules. Enabled rules are checked for cycles on each write. The 1,000-edge limit bounds the proposed source's forward validation walk; it is not a graph-wide depth limit. Conflicts that cannot be resolved safely are rejected without reclaiming historical rules. See failure semantics for exact behavior.

Failure semantics

The plugin skips or rejects a write in the cases below. It never changes a manual rule to satisfy an automatic transition.

Configuration

Configuration fails before Payload starts when the plugin is registered more than once, the redirects slug collides with an existing Collection, a configured Collection or Global is missing or lacks versions.drafts, path options are invalid, conflicting, or name unknown locales, or an override makes a required redirect field incompatible. Without path configuration, no publication hook is added and manual redirects still work. Existing hooks are preserved.

Publication

Automatic rules compare the previously published path with the new published path. The previous path comes from the published version, never from an intermediate draft.

  • First publication, draft saves and autosaves, and unchanged republication create no rule. Deliberately deleted rules are not recreated.
  • Unpublishing or deleting creates no rule; existing rules remain.
  • Restoring an older version counts as a publication transition and is rejected if it creates a cycle.
  • Path resolution disables Payload fallback, so a missing locale value is skipped rather than borrowed from another locale. With Payload's experimental localized publication status, only changed published locales are processed.
  • If the previous published version is no longer retained, no old path is inferred. The plugin keeps no separate history.

Generated redirects share the publication's transaction, so a rejected graph write rolls back the publication. Browser and CDN caches that already received a 301 are not invalidated.

Ownership and conflicts

Existing rule at sourceAutomatic transition
NoneCreate an enabled automatic 301.
Identical automatic ruleLeave it unchanged.
Automatic rule with another destinationUpdate its destination.
Manual ruleLeave it unchanged; skip automatic creation. Publication still succeeds.
Automatic rule edited or disabled by an editorIts origin is now manual; later automatic transitions leave it alone.

Manual create or source change that duplicates a normalized source, including the source of a disabled rule, fails with a Payload validation error on from. The plugin does not record which document owns an automatic rule and does not reclaim historical rules. If returning to an old path would create a cycle, publication fails until an editor resolves the conflicting rule.

URLs and graph validation

  • from and to must be non-empty site-relative paths. Absolute URLs, protocol-relative URLs, schemes, backslashes, and control characters are rejected. Sources cannot contain fragments.
  • Normalization trims whitespace, adds a leading slash, collapses repeated and trailing slashes, and resolves literal or percent-encoded dot segments. It does not percent-decode paths.
  • Store from in encoded form. The plugin does not encode or decode it, and browsers request the encoded form: new URL("/café", "https://example.com").pathname is /caf%C3%A9.
  • The exact query string is part of the source key. Parameter order, repeated parameters, empty values, and percent encoding are preserved.
  • Destination fragments are kept for the browser and are not part of the server request key.
  • Cycle checks follow enabled rules only. Disabled rules still reserve their source.
  • A write follows the proposed enabled chain from to. It is rejected if the chain returns to from, enters an existing loop, or exceeds the 1,000-edge limit, which counts the proposed edge. Exhausting the limit is treated as unverifiable, not safe. The limit bounds only that forward walk; it is not a graph-wide depth limit.
  • A generated source and destination that normalize to the same path write no redirect.
  • The plugin does not scan or repair historical corruption, application routes, external redirects, or CDN rules, and does not compact chains.

Access and transactions

  • Automatic writes use trusted Local API operations with overrideAccess. REST, GraphQL, and user-scoped Local API calls remain subject to the collection's access rules, and anonymous access is disabled by default.
  • On PostgreSQL, graph writes take a transaction-scoped advisory lock before ownership and cycle checks. PostgreSQL releases the lock at commit, rollback, or session end.
  • Graph writes require a request transaction at READ COMMITTED. A missing transaction or another isolation level fails closed.
  • Other database adapters do not have this verified concurrent graph-write guarantee.

Application integration

The library stores and validates rules; it does not match requests or send HTTP responses. Redirect sources and destinations must be site-relative paths; external URLs are not supported. The consuming application looks up enabled rules by exact normalized source and applies the stored destination and status; slash and dot segments are normalized, while query order, repetition, empty values, and encoding remain exact. Destination fragments are preserved. Request methods, route matching, locale prefixes, and browser or CDN caching remain application responsibilities; see the executable Next.js reference.

Next.js proxy

This snippet looks up enabled rules over REST with an exact from match. It serves the page when the lookup fails:

// src/proxy.ts
import { NextResponse, type NextRequest } from "next/server";

type Rule = { to: string; statusCode: "301" | "302" };

// Stored destinations are site-relative paths; anything else fails open.
function isSitePath(to: unknown): to is string {
  return typeof to === "string" && to.startsWith("/") && !to.startsWith("//") && !to.includes("\\");
}

async function findRule(from: string): Promise<Rule | undefined> {
  const query = new URLSearchParams({
    "where[from][equals]": from,
    "where[enabled][equals]": "true",
    limit: "1",
    depth: "0",
  });
  const response = await fetch(new URL(`/api/redirects?${query}`, process.env.PAYLOAD_URL), {
    cache: "no-store",
    signal: AbortSignal.timeout(2_000),
  });
  if (!response.ok) throw new Error(`Redirect lookup failed with ${response.status}`);
  const { docs } = (await response.json()) as { docs: Rule[] };
  const rule = docs[0];
  if (rule && (!isSitePath(rule.to) || !["301", "302"].includes(rule.statusCode))) {
    throw new Error("Redirect lookup returned an invalid rule");
  }
  return rule;
}

export async function proxy(request: NextRequest) {
  if (request.method !== "GET" && request.method !== "HEAD") return NextResponse.next();

  const from = request.nextUrl.pathname.replace(/\/{2,}/g, "/") + request.nextUrl.search;
  try {
    const rule = await findRule(from);
    if (!rule) return NextResponse.next();
    return NextResponse.redirect(
      new URL(rule.to, request.url),
      Number(rule.statusCode) as 301 | 302,
    );
  } catch (error) {
    // Fail open: a lookup outage or an unusable rule serves the page. Return a 503 response here to fail closed.
    console.error(error);
    return NextResponse.next();
  }
}

export const config = { matcher: ["/((?!api|_next|favicon.ico).*)"] };

The lookup gives up after 2 seconds. A timeout, a network error, a non-OK response, an unparsable body, or a rule with an invalid destination or status code all serve the page, as the snippet shows. Adjust the timeout to the lookup's latency budget.

The lookup is anonymous, so the redirects collection needs a read rule that returns only enabled rules to visitors. The default rule requires a signed-in user. Signed-in users keep full read access in the Admin:

redirects({
  overrides: {
    access: {
      read: ({ req }) => (req.user ? true : { enabled: { equals: true } }),
    },
  },
});

The plugin owns rule storage, validation, and the collection's access rules. The application owns request matching, method filtering, trailing-slash and locale handling, the lookup failure policy, the status code applied, and cache headers. If the application runs in the same process as Payload, a server-side Local API find with the same where clause and overrideAccess: true replaces the public read rule.

Compatibility

RequirementSupported or verified
Node.js>=22.23.5 <23, >=24.22.3 <25, or >=26.13.1
Payload>=3.94.1 <4
PostgreSQL adapter@payloadcms/db-postgres >=3.94.1 <4; graph coordination requires READ COMMITTED
Representative verificationPayload 3.94.1 and PostgreSQL 16 in CI; the example app pins Next.js 16.4.6, which CI does not build

Other database adapters and every version in the declared ranges have not been exhaustively tested. Payload's experimental localized publication status follows the behavior provided by Payload.

Documentation

License

MIT. See LICENSE.

Similar plugins