Adds two collections to Payload: one for type definitions and one for entries. Editors create record types and fields in the admin panel, and the plugin builds forms and validates values on save without schema changes. Values are stored in typed SQL columns. Requires Payload 4.0.0-beta.9, Lexical, and either the SQLite or PostgreSQL adapter.
Native runtime-defined collections for Payload CMS (SQLite and PostgreSQL)
Installation
npm i payload-dynamic0
Stars
0
Forks
0
Open Issues
6 days ago
Last Updated
859
Weekly Downloads
v0.1.1
npm Version
121.6 KB
Unpacked Size
0
Dependencies
00 since Nov 15
| 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 |
| Nov 21, 2026 | 0 |
| Nov 20, 2026 | 0 |
| Nov 19, 2026 | 0 |
| Nov 18, 2026 | 0 |
| Nov 17, 2026 | 0 |
| Nov 16, 2026 | 0 |
| Nov 15, 2026 | 0 |
889+889 since Nov 20
| Date | Weekly downloads |
|---|---|
| Dec 5, 2026 | 889 |
| Dec 4, 2026 | 1,087 |
| Dec 3, 2026 | 1,074 |
| Dec 2, 2026 | 1,045 |
| Dec 1, 2026 | 811 |
| Nov 30, 2026 | 591 |
| Nov 29, 2026 | 731 |
| Nov 28, 2026 | 927 |
| Nov 27, 2026 | 664 |
| Nov 26, 2026 | 551 |
| Nov 25, 2026 | 543 |
| Nov 24, 2026 | 525 |
| Nov 23, 2026 | 505 |
| Nov 22, 2026 | 275 |
| Nov 21, 2026 | 0 |
| Nov 20, 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/1464713963-root)<a href="https://payloaddirectory.dev/plugins/1464713963-root"><img src="https://payloaddirectory.dev/badge/1464713963-root.svg" alt="Payload Directory"></a>README
A Payload plugin for defining record types, fields, and relationships in the admin panel. It stores definitions and records in native Payload collections, with typed SQL values, field validation, access control, and reference checks.
Add payloadDynamic(...) to your Payload config. By default, the plugin registers Collections for type definitions and Entries for records. You can set the slug and labels of either collection when you configure the plugin.
flowchart TB
Definitions["Collections<br/>Record types and fields"]
Entries["Entries<br/>Records and values"]
App["Application"]
DB[("SQLite / PostgreSQL")]
Definitions -->|"Form and validation<br/>via definition"| Entries
Entries -->|"REST / Local API"| App
Definitions --> DB
Entries --> DB
For example, create a Posts type with a numeric reading_time field. The plugin builds the form from the definition in Collections and validates the value on save. A post with a reading time of five minutes stores 5 in values[].numberValue in Entries.
The application queries the entries collection with a definition filter for the Posts definition ID. All types share the entries collection, so adding a type in the admin panel requires no schema change.
@payloadcms/ui, @payloadcms/drizzle, and the selected SQL adapter.@payloadcms/[email protected] and Next.js >=16.4.1 <17.0.0.@payloadcms/db-sqlite) or PostgreSQL (@payloadcms/db-postgres). Install only the adapter your app uses; both adapter peers are optional. Other adapters are not supported.@payloadcms/[email protected] is required with either adapter.JSON and Rich Text fields are available only with PostgreSQL. Payload stores these values in separate jsonb columns. In the Local and REST APIs, pass JSON in values[].jsonValue and Lexical documents in values[].richTextValue.
Remove incoming Relationship and Upload references before deleting an entry or file. When you save an entry, the plugin validates its values against the current field settings.
Install the beta from npm.
npm install payload-dynamic@beta
If the npm beta tag is not available yet, install the tarball from the GitHub releases, or install a local copy with npm install ./payload-dynamic-0.2.3.tgz.
Run these commands from the repository root.
npm install
npm run check
npm pack
npm pack builds JavaScript and TypeScript declarations. Install the tarball in your Payload project.
Use the versions above and install the required rich text peer and your chosen database adapter.
# Required peer with either adapter:
npm install @payloadcms/[email protected]
# SQLite application:
npm install @payloadcms/[email protected]
# OR PostgreSQL application:
npm install @payloadcms/[email protected]
The tarball contains dist, this README, the license, and npm's package metadata. It does not include the demo app, tests, local databases, uploads, secrets or source configuration. Use the tarball rather than copying src or linking the development checkout.
Admin components, including PostgresJSONField, resolve through payload-dynamic/react, not paths in the demo source. Regenerate your application's Payload import map with its selected database adapter; PostgreSQL also adds the Lexical editor imports.
To upgrade a local SQLite database from a version before nested fields, start the demo once with DATABASE_PUSH=1 npm run dev using the existing DATABASE_URL, then open /admin so Payload adds the array columns and tables. Use DATABASE_PUSH=0 for subsequent runs. For PostgreSQL, generate and apply a Payload migration before starting the upgraded app.
import { buildConfig, type Access } from 'payload'
import { sqliteAdapter } from '@payloadcms/db-sqlite'
import { payloadDynamic } from 'payload-dynamic'
const signedIn: Access = ({ req }) => Boolean(req.user)
export default buildConfig({
secret: process.env.PAYLOAD_SECRET!,
db: sqliteAdapter({
client: { url: process.env.DATABASE_URL ?? 'file:./payload.db' },
transactionOptions: {},
}),
collections: [{ slug: 'users', auth: true, fields: [] }],
plugins: [payloadDynamic({ canManage: signedIn })],
})
For PostgreSQL, replace the adapter configuration:
import { postgresAdapter } from '@payloadcms/db-postgres'
// Inside buildConfig:
db: postgresAdapter({ pool: { connectionString: process.env.DATABASE_URL! } })
Use your application's normal migration workflow for production. The plugin extends the adapter's schema initialization hooks; it does not enable schema push or run migrations itself.
The root entry exports payloadDynamic and the types PayloadDynamicOptions, PayloadDynamicAccess, and PayloadDynamicWorkspace.
| Option | Type | Meaning |
|---|---|---|
canManage | Payload Access | Fallback access policy for definitions and entries. Apply an appropriate authenticated or role-based policy. |
uploadCollection | Payload CollectionSlug | Optional existing upload collection for upload fields. The plugin protects referenced uploads against deletion. |
uploadWorkspaceField | string | Optional relationship on the upload collection that identifies the file's workspace. |
storagePrefix | string | Optional prefix for the plugin's SQL tables and numeric value index. |
maxNestingDepth | number | Limits nested fields to two by default and allows up to six on PostgreSQL. |
singletons | boolean | Opt in to collection definitions that allow at most one entry. |
workspace | PayloadDynamicWorkspace | Optional membership scope backed by an existing host collection. |
enabled | boolean | Defaults to true. When false, returns the exact host config unchanged, without validating or adding anything. |
collections | { slug?, labels?, access? } | Overrides the definitions collection. Defaults to collections with Collection / Collections labels. |
entries | { slug?, labels?, access?, versions? } | Overrides the records collection. Defaults to entries with Entry / Entries labels. |
Each override is optional. The access object accepts create, read, update, and delete callbacks and replaces canManage for the specified operations. Return a boolean from create. Reads, updates, and deletes also accept native Payload Where constraints. Set labels.singular and labels.plural independently using Payload's collection label format. Scoped lists and breadcrumbs show the selected record type's title.
payloadDynamic({
canManage: signedIn,
collections: {
slug: 'content-types',
labels: { singular: 'Content type', plural: 'Content types' },
},
entries: {
slug: 'content-records',
labels: { singular: 'Record', plural: 'Records' },
},
})
Use distinct slugs that are available in the host app and in SQL. For example, content-types and content_types share a SQL name. With the settings above, use /api/content-types and /api/content-records in REST calls and the same slugs in the Local API. The plugin uses the configured slugs for admin links and relationships. The main SQL tables keep their existing names. When changing slugs in an existing app, update API callers, regenerate Payload types and the import map, and review the generated database migration.
A configured uploadCollection must exist and have uploads enabled.
By default, the plugin uses the existing SQL names collection_definitions and collection_entries. Set storagePrefix to use separate SQL tables when installing the plugin alongside a host that already uses those names. A prefix is 1–8 lowercase letters or digits and starts with a letter.
payloadDynamic({
canManage: signedIn,
storagePrefix: 'content',
collections: { slug: 'content-types' },
entries: { slug: 'content-records' },
})
This example creates content_definitions and content_entries along with prefixed child tables, version tables, and indexes. The REST and Local API slugs are set separately. Choose an unused prefix. The plugin checks SQL names before connecting, including names returned by dbName callbacks and names generated for relationships and PostgreSQL enums. Review the migration generated by the host before applying it. A first installation should create these tables alongside the existing host tables.
An existing plugin installation can keep its current names by leaving the option unset. Changing the prefix changes the target physical table names. To preserve existing data, prepare an explicit migration of definitions, entries, versions, child tables, indexes, foreign keys, and sequences, and verify the data in a restored copy before applying it.
Set maxNestingDepth: 6 on PostgreSQL to enable deeper layouts. Groups and arrays use one level. Blocks and tabs use two levels. Omitting the setting retains the existing two-level layout on PostgreSQL and SQLite.
Depths above two use compact Payload field paths. Definitions keep the root fields array and store nested definitions in f. Entries keep the root values array and use r for rows and i for their items. Use the package's encodePayloadDynamicDefinitionFields and encodePayloadDynamicEntryValues helpers before writing the corresponding arrays through the API. Use decodePayloadDynamicDefinitionFields and decodePayloadDynamicEntryValues to read arrays with the usual field names. Pass the configured depth as the second argument to all four helpers. Regenerate Payload types and the admin import map after changing the layout. Existing installations need an explicit data and schema migration, including retained versions, before enabling a compact layout.
Set entries.preserveValuePresence: true to store valuePresence on typed value rows. Use a row with valuePresence: 'absent' to import an absent value without applying its definition default. Pass null in the typed column to clear an optional value. Include valuePresence: 'absent' with that typed null to record it as absent. The returned marker distinguishes 'absent', 'null' and 'value', including when an empty array reads back as [] for multiple states. A group or tabs value is present when rows contains its singleton item. Sending rows: [] clears that group. To retain a present empty object, pass the singleton item with absent child values. Omitting the entire values array on update preserves saved values.
Set entries.stableRowKeys: true to store a logical rowKey on each array or block row. An importer can pass a source string ID as rowKey. Keys must be unique among sibling rows and remain attached to those rows when reordered. The plugin generates a key for a new row when none is supplied. Existing rows can use their current Payload id as the logical key through the first save. The Payload id still identifies the internal SQL row. rowKey is the scoped identity to use across installations.
Each entry option adds columns to the current and version storage. Review and apply a database migration before enabling these options on existing storage. Previously normalized null and absent values cannot be recovered from legacy rows unless an independent source retained that distinction.
Set singletons: true to enable the optional singleton checkbox on collection definitions. Create a definition with singleton: true to allow at most one current entry. The setting is fixed at creation. Regular collections continue to allow multiple entries.
Use the existing Entries API and scope the lookup to the definition ID. Update the existing entry and use its normal Payload version history. Creating or duplicating a second entry for the same definition fails, even with concurrent requests. Deleting the entry permits a new one.
Use entries: { versions: { drafts: true, maxPerDoc: 0 } } to enable drafts and retain all versions for Entries. The setting applies to every entry in the collection. Choose the retention policy before importing history so later writes preserve the imported versions.
Set entries.retentionByDefinition: true with entries.versions.maxPerDoc: 0 to set different history limits on individual definitions. versionsMaxPerEntry on a definition controls retention after each entry save. Versions tied at the cutoff timestamp stay together. Zero or an unset limit retains all versions. Use database transactions for this option. On SQLite, enable transactions with the adapter's transactionOptions. For existing storage, apply a database migration for the new definition field before enabling the option.
Enable drafts on fresh or empty entry storage. For populated storage, first verify a data backfill on a restored copy that creates a matching published latest version for every existing entry. Applying the schema migration alone leaves existing entries out of Payload's draft views. Dynamic required fields are validated on every draft save, including when Payload's drafts.validate is false.
Run a host database migration before enabling singletons on an existing installation. Existing definitions remain regular collections. The Entries API derives a nullable unique key for current entries, and version history remains attached to the entry. Imports should use the Payload API so the key is applied. When drafts are enabled, deletion checks both the published record and the latest draft for incoming links. Retained historical versions follow the host's Payload deletion policy. Keep the option enabled for databases that contain single-entry collections.
Use an existing collection, such as teams or organizations, as the workspace collection. The host resolves the workspace IDs allowed for each request. The plugin applies that membership to collection definitions, their entries, and their version history alongside the configured operation policies.
payloadDynamic({
canManage: ({ req }) => Boolean(req.user),
collections: {
access: {
create: ({ req }) => canDesignCollections(req.user),
update: ({ req }) => canDesignCollections(req.user),
delete: ({ req }) => canDesignCollections(req.user),
},
},
entries: {
access: { delete: ({ req }) => canDeleteEntries(req.user) },
},
workspace: {
collection: 'teams',
allowedIDs: (req) => teamIDsForUser(req.user),
},
})
The example uses host-defined role and membership functions. Resolve membership from trusted request state and return an empty array for callers without access. Pass overrideAccess: false to the Local API for user requests. Writers need read access to their definition to load its fields. Definition authors need read access to the host workspace record to select it.
Select a workspace when creating a definition. Slugs are unique within that workspace, and the workspace is fixed after creation. Duplicated definitions keep their workspace and receive a new slug. Entries inherit the definition's workspace. Dynamic relationship fields stay within that workspace. The plugin blocks permanent deletion while a workspace owns definitions. The host decides whether archived or trashed workspaces remain eligible in allowedIDs. The host upload collection controls file access.
Enabling workspace mode changes the SQL schema. For an existing installation, prepare a migration that assigns workspace IDs to current definitions and their retained versions before enforcing the required relationship and per-workspace slug index. Keep linked definitions and existing relationship values in the same workspace, or remap those links before enabling the feature. Existing configurations that omit workspace use the same tables and global slug uniqueness.
With uploadWorkspaceField: 'team', configure team as a single, non-localized relationship on the upload collection pointing to the workspace collection. An entry's uploads and Rich Text file references must belong to its definition's workspace, including for privileged saves and version restores. A file remains protected from deletion while current content or a retained version references it. Use database transactions for entry saves and media deletion. On SQLite, enable transactions with the adapter's transactionOptions. The host controls direct file access and should scope its upload collection to workspace members. Assign workspaces to existing uploads before enabling the setting and verify that current and retained content links to files in the same workspace. After activation, the workspace is fixed from upload creation.
Following Payload's plugin pattern and custom component paths, component references are package paths, not paths relative to the consumer's src:
payload-dynamic/react#EntryFields and other explicitly exported client componentspayload-dynamic/react/CollectionsNavigation#CollectionsNavigation (server component, separate from the client barrel)After changing the plugin configuration, generate the import map from the host application's project root using its active Payload config. Use the same database adapter for import-map generation, build, and runtime.
npx payload generate:importmap
Keep the generated import map in your Payload admin application. If you installed an earlier local tarball under payload-dynamic-fields, install the new payload-dynamic tarball, update the plugin import to payloadDynamic, and regenerate the map.
Run the application against a new SQLite file, then separately against a disposable PostgreSQL database. For each adapter: generate the import map, build/start your normal Payload app, log in, create a collection definition and fields, create/edit/read an entry, and verify values survive an application restart. Check validation, access denial and upload reference protection when uploads are configured. Enable schema push only for disposable development databases; use migrations for persistent deployments.
Run npm run test:collections for SQLite integration coverage. Set TEST_DATABASE_URL to a disposable PostgreSQL database to run the PostgreSQL cases as well. The tests create and remove a dedicated PostgreSQL schema.
The root src/app, src/payload.config.ts, and Next configuration form the local demo application and are excluded from the tarball. The host supplies its own Payload application and application dependencies (Next, adapters, and GraphQL).
Create .env in the repository root. Set PAYLOAD_SECRET to a long random value and point DATABASE_URL at a new SQLite file or an empty PostgreSQL database dedicated to the demo.
PAYLOAD_SECRET=replace-with-a-long-random-secret
DATABASE_URL=file:./native-collections.db
Only the demo config selects its adapter from DATABASE_URL. For PostgreSQL, use a URL such as postgres://user:password@localhost:5432/database before generating the demo import map and starting the app. A host application selects its adapter in its own Payload config.
npm install
npm run importmap
DATABASE_PUSH=1 npm run dev
Open /admin to initialize the schema and create the first user. No migration files are provided for the demo. Use DATABASE_PUSH=1 only with a disposable development database. After initialization, use npm run dev for subsequent starts. Run npm run dev:build to build the demo and npm run build to build the npm plugin.
In the admin panel, add a definition under Collections and give its fields stable keys. Then select the new type in Dynamic collections to create records. The plugin validates types, required values, choices, and references against the definition.
Use the Local API to find Posts entries with a reading time of at least five minutes.
const entries = await payload.find({
collection: 'entries',
where: {
and: [
{ definition: { equals: postsDefinitionID } },
{ 'values.fieldKey': { equals: 'reading_time' } },
{ 'values.numberValue': { greater_than_equal: 5 } },
],
},
user,
overrideAccess: false,
})
Use the ID of the Posts definition from Collections for postsDefinitionID. Use your configured entries slug if you changed the default. The and group matches the reading_time key and the minimum value 5 in the same values row in Payload 4.0.0-beta.9. Queries across several keys or ranges need separate conditions for their respective rows. Pass the authenticated Payload user as user and set overrideAccess: false to enforce the collection's access rules.
The plugin indexes field keys, numeric values, dates, and choice values. It also adds the compound index collection_values_key_number_parent_idx on (field_key, number_value, _parent_id). Check your database's query plan for production filters.
Use readPayloadDynamicEntryPage in server code to filter, order, and count a definition's entries in PostgreSQL. The result contains the physical entry IDs for the requested page and the total number of matches. Load those IDs through Payload to apply document hooks and hydrate the records, then put the records in the returned ID order.
import { readPayloadDynamicEntryPage } from 'payload-dynamic'
const page = await readPayloadDynamicEntryPage({
req,
definitionID: postsDefinitionID,
workspaceID: teamID,
where: { category: { in: ['news', 'updates'] } },
sort: ['-published_date', 'title'],
limit: 20,
offset: 40,
})
The helper supports ordering on direct scalar definition fields and the entry's id, title, createdAt, updatedAt, and _status when drafts are enabled and status is shared across locales. Prefix a definition key with values. when it shares a name with entry metadata. Use equals and in with strings or null for text predicates, optionally grouped with and or or. Missing and cleared values compare as null. Set draft: true to read latest versions when drafts are enabled. A draft query fails if multiple versions of an entry in the definition are marked latest because native hydration has no single version to load. Set collection when using a custom entries slug.
The helper uses the request's transaction when one is active. It checks definition and entry read access by default and verifies the workspace if supplied. When it returns undefined, use your existing authorized query for unsupported filters, sorts, adapters, or custom entry access constraints. A server that has already authorized the operation can pass overrideAccess: true and an expected workspaceID.
The default tie-breaker is ascending physical entry ID. A host with its own persistent ID mapping can pass an entryIDOrder callback to supply a PostgreSQL expression for sorting by its ID, followed by the physical ID. Supply this callback only from trusted server code and keep it separate from client query parameters.
An optional top-level leaf field can be removed or changed to another optional leaf type after its values have been cleared in every entry. The server returns 409 with the field label and key while any stored value remains, including 0, false, JSON objects/arrays, or values in an old column. Existing empty rows remain editable after the change; values are never coerced or migrated. Required fields, nested structure changes, and relationship-setting changes still need a separate data migration.
These changes require an active Payload adapter transaction. PostgreSQL uses the same definition row lock for schema changes and entry writes. For SQLite, configure sqliteAdapter({ client: { url: 'file:./payload.db' }, transactionOptions: {} }) to enable its write transactions. Without an active transaction, the existing conservative 409 guard remains in place while entries exist; ordinary entry updates and compatible schema edits keep working. Checks use paginated reads in the request's transaction and do not clean up stored data. Stale schema drafts or entry values are rejected so callers can reload and retry. Direct database writes bypass these protections.
For production, keep schema push disabled. Use payload migrate:create to generate the migration, review its SQL and indexes against a copy of the database, then apply it with payload migrate.
npm run check
npm run test:collections
npm run build
npm run test:package
Report bugs and suggest changes in GitHub Issues. Run the checks above and describe your change when you open a pull request.
Topics
payload plugin presets
Save and apply reusable block configurations as presets from the Payload admin blocks drawer
786.7k/wk37v3
payload puck
Puck drag-and-drop visual page builder embedded in the Payload admin for building pages
772.5k/wk117v3
payload nested docs page tree
Page tree list view for nested docs collections with drag and drop, status badges and live or preview links
771.6k/wk35v3
payload plugin widgets
Dashboard widgets for KPI figures, lists and charts that read from your Payload collections
77536/wk2v3 v4
payload enhanced sidebar
Tabbed sidebar navigation for the Payload admin that groups collections, globals and custom links
76835/wk32v3 v4
payload plugin menu
Editor-friendly navigation menus with dropdowns, headings, icons and per-entry visibility
76126/wk0v3