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.
Redirect management for Payload CMS.
Installation
npm i @klnap/payload-redirect0
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
00 since Nov 22
| Date | Stars |
|---|---|
| Dec 6, 2026 | 0 |
| Dec 5, 2026 | 0 |
| Dec 4, 2026 | 0 |
| Dec 3, 2026 | 0 |
| Dec 2, 2026 | 0 |
| Dec 1, 2026 | 0 |
| Nov 30, 2026 | 0 |
| Nov 29, 2026 | 0 |
| Nov 28, 2026 | 0 |
| Nov 27, 2026 | 0 |
| Nov 26, 2026 | 0 |
| Nov 25, 2026 | 0 |
| Nov 24, 2026 | 0 |
| Nov 23, 2026 | 0 |
| Nov 22, 2026 | 0 |
3.4K+3.4K since Nov 26
| Date | Weekly downloads |
|---|---|
| Dec 6, 2026 | 3,378 |
| Dec 5, 2026 | 3,492 |
| Dec 4, 2026 | 3,544 |
| Dec 3, 2026 | 3,193 |
| Dec 2, 2026 | 3,123 |
| Dec 1, 2026 | 2,959 |
| Nov 30, 2026 | 1,253 |
| Nov 29, 2026 | 757 |
| Nov 28, 2026 | 542 |
| Nov 27, 2026 | 0 |
| Nov 26, 2026 | 0 |
Each point is npm's rolling 7-day download count.
Health Score
Composite score based on GitHub activity, stars, npm downloads, publish recency, dependency count, and package size.
Badge for your README
[](https://payloaddirectory.dev/plugins/1472041920-root)<a href="https://payloaddirectory.dev/plugins/1472041920-root"><img src="https://payloaddirectory.dev/badge/1472041920-root.svg" alt="Payload Directory"></a>README
@klnap/payload-redirectAutomatic and manual redirects for Payload CMS. Tracks published path changes across Collections and Globals and stores redirect rules using native Payload collections.
301 redirects for published path changes when prior publication history is available, while preserving manual rules.301 and temporary 302 rules.bun add @klnap/payload-redirect
# or
npm install @klnap/payload-redirect
Payload is a peer dependency; install @payloadcms/db-postgres when using PostgreSQL.
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()],
});
| From | To | Status | Use |
|---|---|---|---|
/old-guide | /guides/start#installation | 301 | Permanent page move |
/summer | /offers?utm_source=sms | 302 | Temporary 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.
| Option | Description |
|---|---|
collections, globals | Automatic path configuration by entity slug. Choose one of path, paths, or getPath. |
localePrefixes | Optional per-locale prefixes for templates. |
overrides | Customize 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.
The plugin skips or rejects a write in the cases below. It never changes a manual rule to satisfy an automatic transition.
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.
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.
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.
| Existing rule at source | Automatic transition |
|---|---|
| None | Create an enabled automatic 301. |
| Identical automatic rule | Leave it unchanged. |
| Automatic rule with another destination | Update its destination. |
| Manual rule | Leave it unchanged; skip automatic creation. Publication still succeeds. |
| Automatic rule edited or disabled by an editor | Its 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.
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.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.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.overrideAccess. REST, GraphQL, and user-scoped Local API calls remain subject to the collection's access rules, and anonymous access is disabled by default.READ COMMITTED. A missing transaction or another isolation level fails closed.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.
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.
| Requirement | Supported 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 verification | Payload 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.
MIT. See LICENSE.
Topics
path
Stored, indexed URL paths for Payload 4 pages and posts built from a parent and a slug
75270/wk10v4
redirects
Manage internal and external redirects from the Payload admin panel
100200.1k/wk46.1kv3 v4
payload slug
Slug field with Auto/Manual modes, nested source paths, localization and enforced uniqueness
802.4k/wk0v3
redirects
Editor-managed redirects for Payload 4 with indexed lookups, regex support and move-based redirect suggestions
72187/wk10v4
payload slug redirects
Records slug changes in Payload and redirects old URLs to the current slug in Next.js
6471/wk3v3
localized slugs
Copies localized slug and full path values into a per-locale localizedSlugs field for multi-language Payload sites
7881/wk9v3