Create a custom field
When the built-in field types don't fit, add your own with a plugin. This guide builds a color field that stores a hex color such as #ff6600.
Custom fields are part of your deployment, so they need a self-hosted instance with a pagescms.config.ts.
1. Define the field
The definition describes the value: its label, default and validation. It runs in both the browser and the server, so keep it synchronous and free of UI code, secrets and server APIs.
import { z } from 'zod'
import type { FieldDefinition } from 'pagescms/plugins/client'
export const label = 'Color'
export const defaultValue = '#000000'
export const schema: FieldDefinition['schema'] = () =>
z.string().regex(/^#[0-9a-f]{6}$/i, 'Use a six-digit hex color')2. Build the editor
The editor is a React component. It receives the current value and reports changes through onChange; it never saves directly. renderField wraps your input in the standard label, description and error layout.
import type { FieldRendererProps } from 'pagescms/plugins/client'
export default function ColorField(props: FieldRendererProps) {
return props.renderField(
<input
id={props.id}
type="color"
value={typeof props.value === 'string' ? props.value : '#000000'}
disabled={props.disabled}
required={props.required}
aria-invalid={props.invalid || undefined}
aria-describedby={props.errorId}
onChange={(event) => props.onChange(event.target.value)}
/>,
)
}3. Register the plugin
A plugin has up to three entry points. This field needs two: shared for the definition, used on both sides, and client for the lazily loaded editor.
import type { SharedPluginModule } from 'pagescms'
import * as definition from './definition'
export default (() => ({
fields: { color: { definition } },
})) satisfies SharedPluginModuleimport type { ClientPluginModule } from 'pagescms'
export default (() => ({
fields: { color: { editor: () => import('./editor') } },
})) satisfies ClientPluginModuleAdd it to the plugins array, keeping your existing target and plugins:
import { defineConfig, definePlugin } from 'pagescms'
export default defineConfig({
target: 'node',
plugins: [
definePlugin({
id: 'color',
shared: new URL('./plugins/color/shared.ts', import.meta.url),
client: new URL('./plugins/color/client.ts', import.meta.url),
}),
],
})Restart the dev server after changing registrations, and rebuild for production. Plugins are never discovered automatically.
4. Use it
Add the field to a collection or file in .pages.yml:
fields:
- name: accent
type: colorCheck that:
- a valid color saves and reloads;
- an invalid value shows the validation message;
readonly: trueprevents edits;- it works with the keyboard, and inside lists if you'll use it there.
Next
- Transform values on read and write, or show the field in collection lists: Custom field API
- Add routes, sign-in providers or admin pages: Plugins