Generates prefixed, type-safe TypeID identifiers for Payload collections. In Primary mode the TypeID becomes the native ID; in Secondary mode a unique type_id field is added and native IDs and relationships stay as they are. It installs PostgreSQL CHECK constraints and triggers at startup to enforce format, prefix and immutability. It needs Payload 3.1.1 or later, Node 22.14 or later and PostgreSQL for the guards.
TypeID identifiers for Payload CMS, as primary IDs or secondary semantic identity.
Installation
npm i @klnap/payload-typeid0
Stars
0
Forks
0
Open Issues
Yesterday
Last Updated
3.3k
Weekly Downloads
v0.3.16
npm Version
189.3 KB
Unpacked Size
0
Dependencies
00 since Nov 22
| Date | Stars |
|---|---|
| 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 |
Trends appear once the first and last snapshots are 7 days apart. Collecting since Nov 29 — 7 daily snapshots so far.
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/1474446907-root)<a href="https://payloaddirectory.dev/plugins/1474446907-root"><img src="https://payloaddirectory.dev/badge/1474446907-root.svg" alt="Payload Directory"></a>README
Type-safe TypeID identifiers for Payload CMS with PostgreSQL integrity guards. Use TypeID as Payload's native ID or add type_id while preserving native IDs and relationships.
article_01m8d47saaepfr8kaw7mqdxs1h
author_01m8d47sabf8ca5x5s9smzr0qz
bun add @klnap/payload-typeid
# or
npm install @klnap/payload-typeid
>=22.14.0. CI tests the packed tarball on Node.js 22.14.0, 22, 24, and 26.^3.1.1. CI runs the primary PostgreSQL suite on Payload 3.1.1, 3.68.4, 3.71.0, and 3.94.2 (the pinned latest). The secondary adoption suite runs in CI only on the latest pinned Payload, 3.94.2.| Primary (default) | Secondary | |
|---|---|---|
| TypeID | Native id | Additional type_id |
| Lookup/relationships | TypeID | Native IDs preserved |
| Existing database | Migrate IDs/references or use a new database | Schema migration/backfill |
| Best fit | Semantic native IDs | Retain existing model |
id. Choose Secondary to keep native IDs and relationships.type_id through a staged migration. See Existing-database adoption.Choose Primary when TypeID should be Payload's native ID. Managed collections require the PostgreSQL adapter setting idType: "uuid". This setting is adapter-wide: @payloadcms/db-postgres uses it as the default ID type for every collection. Unmanaged collections and collections with custom.typeId: false also get UUID native IDs. Plan for this before choosing Primary. Plugin database integration handles TypeID storage.
Excerpt from the Payload configuration:
import { postgresAdapter } from "@payloadcms/db-postgres";
import { typeId } from "@klnap/payload-typeid";
db: postgresAdapter({
idType: "uuid",
pool: { connectionString: process.env.DATABASE_URL! },
}),
plugins: [typeId()],
Choose Secondary to retain native IDs and relationships. findByID() and routes stay native; the indexed type_id supports TypeID lookups.
Excerpt from the Payload configuration:
import { typeId } from "@klnap/payload-typeid";
plugins: [typeId({ strategy: "secondary" })],
Keep the adapter's native ID type. Secondary does not require idType: "uuid". Use native Payload migrations in production; development schema push changes schema only. Existing data needs a staged migration and backfill. Startup never backfills; see Existing-database adoption.
Install the package (see Install).
Register the plugin in the Payload configuration:
import { buildConfig } from "payload";
import { postgresAdapter } from "@payloadcms/db-postgres";
import { typeId } from "@klnap/payload-typeid";
export default buildConfig({
db: postgresAdapter({
idType: "uuid", // omit for Secondary
pool: { connectionString: process.env.DATABASE_URL! },
}),
collections: [
// your collections
],
plugins: [typeId()],
});
Create the schema with your Payload migration workflow, then start the app. Startup validates the schema and installs the PostgreSQL guards. The payload migrate step is confirmed for Primary (uuid) and for Secondary with serial or UUID IDs in local runs, not CI; see Verification status.
Every collection is managed by default. Set the strategy plugin-wide; collection custom.typeId overrides the central collections option.
import { typeId } from "@klnap/payload-typeid";
typeId({
strategy: "secondary",
collections: {
articles: "article", // explicit, stable prefix
authors: true, // derive prefix from slug
categories: false, // opt out and keep native IDs
},
});
A collection's own setting is set with custom.typeId. This excerpt assumes CollectionConfig is imported from payload:
export const Articles: CollectionConfig = {
slug: "articles",
custom: { typeId: "article" },
fields: [],
};
Payload's CollectionCustom accepts Record<string, any> in the inspected releases, so custom.typeId needs no module augmentation.
Precedence is model custom.typeId, then central collections[slug], then the derived default.
| Value | Effective result |
|---|---|
true | Managed; prefix derived from the collection slug (same as omitted). |
| prefix string | Managed; prefix used exactly as written. |
false | Unmanaged; native ID strategy preserved (opt-out). |
omitted / undefined | Inherits the central value; derived prefix when none exists. |
A model false opts out even when the central value names the collection. Shadowed central prefixes are not validated and cannot cause collisions. Structural errors in shadowed central values, such as invalid types or unknown collection slugs, still fail configuration.
typeId() sets its plugin order so Payload 3.94.x honors it. Payload 3.1.1 applies plugins in array order. On 3.1.1, register typeId() after plugins that add collections:
plugins: [otherPlugin(), typeId()],
Globals are not collection documents. custom.typeId on a Global must be false or omitted. true and prefix strings throw a configuration error.
^([a-z]([a-z_]{0,61}[a-z])?)?$, be at most 63 characters, and not be empty.dbName are ignored. The plugin replaces _ with -, calls Payload's formatLabels(slug).singular from the Payload root entry, splits on spaces, lowercases the words, and joins them with _.APIKeys, HTMLPages, FAQs, a-b, users-2fa, uploads-v2, café-menus, and email/templates. The error recommends an explicit prefix.articles to article, article-authors to article_author, ArticleAuthors to article_author, Article_Tags to article_tag, people to person, criteria to criterion, news to news, and data to datum. Pluralization can produce an undesirable word such as datum; use an explicit prefix to fix it.Unknown collections, duplicate prefixes, invalid settings, the obsolete custom.typeid key, and managed field conflicts fail configuration. A managed collection with its own root-level id field, including one inside a flattened row, collapsible, or unnamed-tab layout, also fails. Nested id fields in groups, arrays, blocks, and named tabs are unaffected. In Secondary, an existing type_id field is rejected rather than overwritten.
Resubmitting an unchanged identity is accepted; changing or clearing it returns a Payload APIError (400). PostgreSQL guards also protect ordinary writes.
| Operation | Primary | Secondary |
|---|---|---|
| Create | Generates id; rejects supplied ID | Generates type_id; rejects supplied value |
| Update | Keeps omitted/unchanged ID; rejects mutation | Keeps omitted/unchanged value; rejects mutation |
| Bulk update | Omit id from data | Rejects type_id in data |
| Duplicate | New native TypeID | New TypeID; native ID behavior |
| Draft/publish/restore | Preserves document ID | Preserves TypeID; versions match parent |
| Lookup/relationships | TypeID is native ID | Use native IDs; query type_id |
REST, GraphQL, Local API, and Admin follow this contract. overrideAccess skips Payload access checks, not hooks or database guards.
id in REST, GraphQL, Admin, and the Local API. In Secondary, native IDs stay in routes and findByID(); query type_id for TypeID lookups.type_id column, a unique index per collection, and parent-identity checks for version rows. Primary text IDs use more index and storage space than native UUIDs. See Performance.idType: "uuid" is adapter-wide, so unmanaged and custom.typeId: false collections also get UUID native IDs. Secondary does not need it.| Guarantee | Primary | Secondary |
|---|---|---|
| Format and configured prefix | CHECK constraint | CHECK constraint |
| Insert-time generation | Trigger generates an omitted native id | Payload hook generates type_id |
| Uniqueness | Native primary key per collection | Unique index per collection |
| Immutability | Trigger rejects changed id | Trigger rejects changed document/version identity |
| Version consistency | Native Payload references | Trigger requires version identity to match its parent |
Primary uses text-compatible ID/relationship/version columns (idType: "uuid"). Secondary preserves native IDs/relationships and requires text type_id plus per-collection uniqueness. SQL checks syntax, prefix, and suffix, not UUID version or variant bits. Payload handles relationships and foreign keys.
On each Payload start, the plugin installs missing guards for every managed table:
CHECK on id (prefix, 26 Base32 characters, first character 0–7), a BEFORE INSERT OR UPDATE trigger that generates an ID when id is NULL, and a trigger branch that rejects changes to id.CHECK for non-null type_id values and a BEFORE UPDATE trigger that rejects identity changes. Version tables receive a prefix/format/non-null check and a trigger that requires version_type_id to match the parent document and rejects later changes. Version tables have no uniqueness constraint, because many versions belong to one document.Startup behavior:
onInit through the adapter's pool. The whole script is one query, so a failure installs nothing. Other adapters log a warning and keep application-level rules only.NOT NULL, and a valid single-column unique index. Missing required columns or indexes fail closed.pg_proc, pg_get_constraintdef (with convalidated), and pg_get_triggerdef definitions, including trigger activation, event, function OID, and arguments. Mismatches fail with a manual repair instruction. Startup never drops or replaces an incompatible object.CHECK. Otherwise startup fails before any guard is installed.schemaName. Without one, they are unqualified, matching Payload's tables.CHECKs cover managed main tables. Versions and join tables reference those IDs through foreign keys, and the integration suite asserts both directions.DROP/TRUNCATE, backup restores, privileged session_replication_role = replica sessions when a trigger is origin-enabled, and non-PostgreSQL adapters. Database administrators can alter guards.This section covers Primary adoption, Secondary setup, backfill, and recovery. Payload and the application own schema migrations. The plugin never rewrites existing IDs or relationships, runs a data backfill at startup, or repairs incompatible database objects. Startup installs only missing guards.
Secondary adoption preserves native IDs and relations, but it is a staged schema and data migration. Use a maintenance window: stop API/Admin writes, workers, scheduled jobs, imports, and other database writers until activation is complete. Online migration is unsupported.
pg_restore --list checks an archive's contents but does not prove a successful restore.dbName, schema, and version table). Prefer explicit prefixes for identifiers used externally.payload migrate application step is confirmed for Primary (uuid) and for Secondary with serial or UUID IDs in local runs, not CI; see Verification status.Payload's PostgreSQL schema builder omits NOT NULL for fields with conditional Admin visibility. Secondary hides type_id on create and shows it read-only on later document forms, so the plugin uses the adapter's schema hooks to mark document and version identity columns required. The hook supports the rawTables schema path and the completed Drizzle schema path used by older Payload releases. Review generated migrations and future schema changes as usual. Do not make manual SQL edits that leave migration snapshots inconsistent.
Primary replaces the managed native ID model with TypeID IDs. It requires PostgreSQL adapter idType: "uuid", while the persisted prefixed IDs and related references are text-compatible. The plugin does not convert serial or UUID IDs, relationship values, version data, or foreign keys. Enabling primary TypeIDs on an existing collection changes its primary key and relationship types. Before activation, complete and verify an operator-owned migration of IDs, all references, and constraints, or use a new database. Existing rows must satisfy the configured TypeID prefix/format check before guards can be installed.
Create the final Payload configuration with typeId({ strategy: "secondary" }). Run payload migrate:create and review the generated migration and snapshot. The plugin's adapter schema hook makes type_id and versioned collections' version_type_id non-null in the generated schema. Payload also generates the per-collection unique index for type_id. Apply the reviewed migration with your application's migration workflow; see Verification status. Then start the normal application. Startup fails if required physical schema invariants (columns, nullability, or unique index) are missing. Missing compatible format and immutability guards are installed transactionally when the startup role has the required DDL permissions. Incompatible existing guards fail closed.
Do not treat registration alone or development schema push as complete Secondary database setup. The repository-only playground has a disposable preparation script. It is not the production migration procedure.
The following process preserves existing serial/integer and UUID IDs and their relationship values. Those two ID families were exercised in PostgreSQL 16 with Payload 3.94.2. Other custom ID representations are unverified.
Use a temporary migration configuration without the plugin. Add optional text fields named type_id to each collection to be managed. Payload adds the corresponding version_type_id for versioned collections. Generate and apply a migration that adds nullable columns only. Do not add NOT NULL or uniqueness before backfill.
For example, the intended stage-one SQL for articles and authors is:
ALTER TABLE public.articles ADD COLUMN type_id varchar;
ALTER TABLE public.authors ADD COLUMN type_id varchar;
ALTER TABLE public._articles_v ADD COLUMN version_type_id varchar;
Use the table names and text-compatible type emitted for the actual adapter. Do not edit generated migration SQL without checking its snapshot. Payload's next migrate:create uses the latest snapshot as its before-state. Manually changing DDL alone can make later diffs incorrect.
The npm archive includes migrations/backfill-secondary.mjs. It is an operator-invoked script, not part of plugin startup. Create a JSON file with the exact schema, managed collection tables and prefixes, optional version tables, and batch size:
{
"schema": "public",
"batchSize": 250,
"collections": [
{
"slug": "articles",
"table": "articles",
"prefix": "article",
"versionsTable": "_articles_v"
},
{ "slug": "authors", "table": "authors", "prefix": "author" }
]
}
Run from the application root with DATABASE_URL pointing to the migration database:
DATABASE_URL="$MIGRATION_DATABASE_URL" \
node node_modules/@klnap/payload-typeid/migrations/backfill-secondary.mjs ./typeid-backfill.json
The script resolves the PostgreSQL driver from the installed @payloadcms/db-postgres adapter. batchSize defaults to 250 and accepts integers from 1 to 5,000. Schema and table identifiers must be simple lowercase PostgreSQL names; the script validates and quotes them.
The script rejects malformed, wrong-prefix, or duplicate existing document values, and non-null version values that conflict with their parent. It preserves valid assigned values and fills only NULL document fields. Empty strings and other invalid values are not treated as missing. Each ordered FOR UPDATE batch is committed separately, and version identity is updated in batches. A failure rolls back the current batch, while earlier commits remain. Rerunning the same command resumes by selecting missing values and does not replace established identities. Do not run multiple copies, and do not allow application writes during the backfill.
For versioned collections, the script sets historical version_type_id to the current parent type_id. Multiple historical rows intentionally share one value; the version field is not unique. Without this backfill, an update whose originalDoc is reconstructed from an older version may not contain the new field. New UUIDv7 timestamps represent allocation time, not original document creation time.
Script success does not prove every application invariant. Separately verify that no document identity is null, all version rows have a parent and matching identity, relation values and foreign keys remain valid, the existing IDs and business content are unchanged, and publication and version counts match the recorded baseline. The script does not check every catalog object, final NOT NULL, or unique-index state. It writes identity columns directly and does not route content through Local API hooks.
After the backfill and data checks, switch to the final configuration with typeId({ strategy: "secondary" }). Remove the temporary application-owned type_id field to avoid a field-name collision. Run payload migrate:create again and review the generated migration. The final configuration's plugin schema hook makes the generated migration set both document and version identity columns NOT NULL, and the generated snapshot records the required state. Payload generates the unique index for the document field. Inspect the SQL and snapshot before applying.
Confirm that the generated migration includes SET NOT NULL for every managed type_id and versioned version_type_id, plus one unique index per managed document field. If not, stop and inspect the Payload version, adapter, plugin registration, snapshot, and final configuration. Do not edit only the SQL. Review rollback SQL; do not drop populated columns by default.
Apply the final migration with your application's migration workflow. Only then start the normal app with Secondary enabled. Startup validates text-compatible field types, NOT NULL, a valid single-column unique index, and existing guard definitions and state. It installs missing compatible format and immutability guards transactionally and fails closed on incompatible schema or guard objects.
Before reopening writes, verify that native lookups and relationships still work, TypeID field queries resolve the intended records, newly created documents receive type_id, and updates preserve it. Check that PostgreSQL catalogs show the expected constraints, index, and active triggers. Test that an invalid prefix, a duplicate, and an ordinary SQL identity mutation are rejected.
Confirmed in local runs of the tests/fixtures/native-migrations procedure (not CI). Each run used a consumer project outside the repository that installed @klnap/[email protected] from the npm registry, with Payload 3.94.2, @payloadcms/db-postgres 3.94.2, PostgreSQL 16 (postgres:16-alpine), and Node 26.13.1. payload migrate applied a generated initial migration and a later schema migration, and the fixture checks passed after each migration and after restart. Confirmed for the Primary strategy with idType: "uuid", and for the Secondary strategy with serial and UUID native IDs. The checks cover the schema, relationships, and version rows (see tests/fixtures/native-migrations/verify.mjs).
Not confirmed: CI coverage (no CI job runs payload migrate), other Payload versions, the Node 22.14 minimum, payload migrate:down, guard and trigger behavior, and production databases. The integration suite directly exercised equivalent PostgreSQL DDL and the packaged backfill; that is not an end-to-end CLI migration test. Confirm the application-owned migration in your application and toolchain before production use.
Other verified coverage:
A prefix is part of every identifier and the installed guard definitions. Changing it does not affect only future documents. Old values retain the previous prefix, and existing constraints and triggers no longer match the new configuration. Startup fails closed. The plugin does not rewrite IDs or replace guards. Coordinate an operator-owned data and guard migration before changing the setting.
Switching Primary to Secondary, or Secondary to Primary, is not a configuration-only migration. The plugin does not move values between id and type_id, rewrite foreign keys, alter primary keys, or remove old guards. Removing Secondary stops plugin management but leaves its column, index, and values in place. Roll back application configuration separately from schema and data changes. Restore a tested backup only when intentionally reverting committed data.
import {
fromUUID,
generateTypeId,
isTypeId,
parseTypeId,
toUUID,
type TypeID,
} from "@klnap/payload-typeid";
const id: TypeID<"article"> = generateTypeId("article");
const parsed = parseTypeId(id, "article"); // checks the expected prefix at runtime
const sameId = fromUUID("article", toUUID(id));
isTypeId(sameId, "article"); // true
generateTypeId(prefix) creates a UUIDv7-backed TypeID. parseTypeId(unknown) returns { prefix, uuid }, throws TypeError on invalid input, and checks an optional prefix at runtime. isTypeId(value[, prefix]) validates and narrows. fromUUID(prefix, uuid) encodes a canonical UUID of any version; toUUID(value) decodes it.
Exports: TypeID<Prefix>, TypeIdOptions (strategy, collections), and TypeIdStrategy ("primary" | "secondary"). Utilities accept prefixless TypeIDs; collection prefixes cannot be empty. Branding is compile-time only, so validate untrusted input at runtime. Generated Payload types do not infer prefixes. Secondary type_id may type as string | null despite the SQL NOT NULL. UUIDv7 is not strictly monotonic within one millisecond or across processes. Primary id remains a Payload-generated string. Generation and conversion are synchronous, stateless, and local; they do not access the database or network.
See the performance guide for the measured local snapshot and reproduction steps. Secondary adds index and storage cost. Primary is not guaranteed faster. The published numbers come from one local run on one dataset, so treat them as descriptive, not service-level expectations.
isTypeId(value, "article") or parseTypeId(value, "article").overrideAccess: false. overrideAccess skips Payload access checks, not hooks or database guards.MIT © klnap. See LICENSE.
Topics
payload surrealdb
SurrealDB database adapter for Payload CMS v3 and v4 using its PostgreSQL-compatible SQL interface
77268/wk3v3 v4
payload default value gen
Generate custom default ID values such as UUIDs for selected Payload collections
3530/wk3v3
payload upstash
Upstash Redis key-value adapter for Payload's built-in KV store
82333/wk7v3 v4
payload kv
Store counters, feeds and expiring data in Redis or KV stores while querying them as normal Payload fields
771.4k/wk0v3 v4
payload locale snapshot
Prevents loss of other-locale translations in localized blocks and arrays when saving with the Postgres adapter
6663/wk3v3
payload kv cloudflare
Payload KV adapter that stores key-value data in Cloudflare Workers KV
6663/wk0v3 v4