**BREAKING:** Modifies fields types which are allowed to be passed in to upload, link, and blocks lexical features. Can break your types even if no sub-richText editor is passed in
* feat(db-postgres): configurable custom schema to use
* test(db-postgres): use public schema
* chore(db-postgres): simplify drop schema
* chore: add postgres-custom-schema test to ci
* chore: add custom schema to postgres ci
* chore(db-postgres): custom schema in migrate
* chore: ci postgres wait condition
* fix(db-postgres): find missing path for nested arrays
* fix(db-postgres): set _parentID for array nested localized fields
* fix: afterRead fallbackLocale causing locale data loss
* chore(richtext-lexical): updated args to match payload type change
* test: simplify localization e2e duplicate
* feat(plugin-search): pass `req` to beforeSync to support using transactions
* fix(plugin-search): hooks do not respect transactions
* chore(plugin-search): await hooks
* chore: remove eslint disable comments
* fix: filterOptions errors cause transaction to abort
* fix(db-mongodb): uncaught abortTransaction race condition
* chore: remove test that is not adding value
* chore: limit options on errors in filterOptions
* chore: limit options when an error occurs in filterOptions
* feat(db-postgres): WIP adds idType to use uuid or serial id columns
* chore: add postgres-uuid test ci
* chore: add postgres-uuid env vars
* chore: sanitizeQueryValue prevent invalid types
* fix(db-postgres): invalid parentID of nested arrays
* feat(richtext-lexical): Update lexical from 0.12.6 to 0.13.1, port over all useful changes from playground
* chore: upgrade lexical version used in monorepo
* Updated templates and readme to note conflicting routes
* Move information in readmes to blockquotes and move next-api to just next
* Remove unnecessary notes
* feat: extend transactions to cover after and beforeOperation hooks
* feat: use transactions in refresh operation
* docs: add req to beforeOperation and afterOperation args
* chore: use transactions in tests running mongoDB memory server
* chore: relationship test async setup changes
* chore: async test fix
* chore: flaky e2e localization test
* chore: scaffolds fix for replacing curly brackets in email with lexical editor
* fix: submissionData not passed to nested fields
* chore: adds int test for lexical serializer
---------
Co-authored-by: Alessio Gravili <alessio@bonfireleads.com>
* fix: object equality query by prioritizing value key in relationship queries
* chore: adds e2e & int test
* chore: updates test for REST querying on poly relationships
* Adds a check for the first tab and e2e test for custom ID
* Add support for ids in any order inside an unnamed tab
* Update tests for rows
* Minor fixes and remove dead commented code
* fix: adds updated object-id validation to isValidID
* chore: adds check to see if value is of type string or object
* chore: needs to return false if value not of type object or string
* fix: allow json field to be saved empty and reflect value changes
* fix: reverts change to json field validation
* chore: wraps more JSON field logic with a try/catch
* fix for supporting hasMany property in text field
* Updated docs
* handle text case types for schema and graphql schema
* fix unit test for required failing
* add unit test for has many text field
* add end to end test for has many on text field creation
* support has many feature for text field on postgres
---------
Co-authored-by: Chris Heinz <chrisi.heinz@web.de>
* chore: scaffolds out fix for postgres issues with custom ids in versions
* fix(db-postgres): queryDrafts returns undefined doc.id
* chore(db-postgres): fix build
* fix: removes extra custom id field from versions buildCollectionFields
* chore: comments test/versions seeding back in
* fix buildCollectionFields version group fields
* fix: id field can be edited after saving a document with custom ids
* chore: updates versions custom ID test
---------
Co-authored-by: PatrikKozak <patrik@payloadcms.com>
BREAKING: An unpopulated, internal link node no longer saves the doc id under fields.doc.value.id. Now, it saves it under fields.doc.value.
Migration inside of payload is automatic. If you are reading from the link node inside of your frontend, though, you will have to adjust it.
The version property of the link and autoLink node has been changed from 1 to 2.
* fix(richtext-lexical): Link: allow phone numbers as URLs starting with tel:+
* feat(richtext-lexical): Link Feature: immediately validate URL field in drawer form
* Remove console log
* feat(richtext-lexical): ability to configure link feature enabled relations on a field-level
* feat(richtext-lexical): ability to configure Relationship feature enabled relations on a field-level
* chore(richtext-lexical): Improve Link feature props typing
* chore(richtext-lexical): Improve Link and Relationship feature props typing
* fix(richtext-lexical): Link drawer types
* chore: merge conflict resolve
* chore(richtext-lexical): Link Feature: add comments that explain how getBaseFields works
* chore(richtext-lexical): lazy import all React things
* chore(richtext-lexical): use useMemo for lazy-loaded React Components to prevent lag and flashes when parent component re-renders
* chore: make exportPointerFiles.ts script usable for other packages as well by hoisting it up to the workspace root and making it configurable
* chore(richtext-lexical): make sure no client-side code is imported by default from Features
* chore(richtext-lexical): remove unnecessary scss files
* chore(richtext-lexical): adjust package.json exports
* chore(richtext-*): lazy-import Field & Cell Components, move Client-only exports to /components subpath export
* chore(richtext-lexical): make sure nothing client-side is directly exported from the / subpath export anymore
* add missing imports
* chore: remove breaking changes for Slate
* LazyCellComponent & LazyFieldComponent
* chore(richtext-lexical): Add int test which reproduces the issue
* chore: Remove unnecessary await in core afterRead promise
* fix(richtext-lexical): re-use recurseNestedFields from payload instead of using own recurseNestedFields
* chore(richtext-lexical): pass in missing properties which are available in the core afterRead hook
* chore: remove unnecessary block
* chore(richtext-lexical): Add a hint that the slash menu exists to the user
* Update LexicalEditor.tsx
---------
Co-authored-by: Alessio Gravili <70709113+AlessioGr@users.noreply.github.com>
* fix(richtext-lexical): make sure block fields are wrapped in a uniquely-named group
* chore: remove redundant hook
* chore(richtext-lexical): attempt to fix unnecessary unsaved changes warning regression
* cleanup everything
* chore: more cleanup
* debug
* looks like properly cloning the formdata for setting initial state fixes the issue where the old formdata is updated even if node.setFields is not called
* chore: fix e2e tests
* chore: fix e2e tests (a selector has changed)
* chore: fix int tests (due to new blocks data format)
* chore: fix incorrect insert block commands in drawer
* chore: add new e2e test
* chore: fail e2e tests when there are browser console errors
* fix(breaking): beforeInput and afterInput: fix missing key errors, consistent typing and cases in name
* chore: new lexical int tests and working test structure
* chore: more int tests, and better lexical collection structure
* fix(richtext-lexical): Blocks: unnecessary saving node value when initially opening a document
* feat(richtext-lexical): 'bottom' position value for plugins
* feat: TestRecorderFeature
* chore: restructuring to seed and clear db before each test
* chore: make sure all tests pass
* chore: make sure indexes are created in seed.ts - this fixes one erroring test
* chore: speed up test runs through db snapshots
* chore: support drizzle when resetting db
* chore: simplify seeding process, by moving boilerplate db reset / snapshot logic into a wrapper function
* chore: add new seeding process to admin test suite
* chore(deps): upgrade jest and playwright
* chore: make sure mongoose-specific tests are not skipped
* chore: fix point test, which was depending on another test (that's bad!)
* chore: fix incorrect import
* chore: remove unnecessary comments
* chore: clearly label lexicalE2E test file as todo
* chore: simplify seed logic
* chore: move versions test suite to new seed system
Fixes#3904
* fix(db-mongodb): improve find query performance
* fix: add optimization to other operations which use pagination: findGlobalVersions, findVersions, queryDrafts
* fix: index createdAt field by default
* feat(live-preview): another oen
* wip: changelog script
* wippppp
* chore: this worked
* wip: changelog working
* chore(script): working changelog gen
* chore(script): update changelog during release
* chore(richtext-lexical): add jsdocs for afterReadPromise in GraphQL
* feat(richtext-lexical): HTML Serializer
* chore(richtext-lexical): adjust comment
* chore(richtext-lexical): change the way the html serializer works
* chore: working html converter field, improve various exports
* feat: link and heading html serializers
* fix: populationPromises not being added properly
* feat: allow html serializers to be async
* feat: upload html serializer
* feat: text format => html
* feat: lists => html
* feat: Quote => html
* chore: improve Checklist => html conversion, by passing in the full parent to converters
* feat: pass collection, global and field props to collection, global and field hooks - where applicable
* fix: initial request context not set for all operations
* chore: add tests which check the collection prop for collection hooks
* feat: add context to props of global hooks
* chore: add global tests for global and field props
* chore: int tests: use JSON instead of object hashes
* Fix generate:types bug #3697
generateEntityDeclarations function creates mismatched type names. We'll simply use the existing Config type instead.
* code cleanup
* fix(bundler-webpack): better node_modules resolution
* chore: see if retries are affecting new webpack changes
* chore: reinstate retries
This reverts commit 96989295ba.
* chore: default to process.cwd() if cannot find node_modules path
* feat: update templates to 2.0 and support create-payload-app
* chore: rich text updates
* chore(templates): remove mongoURL
* chore: migrates rich text fields in website
* chore: manually aliases dotenv in templates
* chore: installs new beta in website template
* chore: type issues
* chore (template): add alias for fs to website template
* chore: more template updates
---------
Co-authored-by: James <james@trbl.design>
Co-authored-by: Dan Ribbens <dan.ribbens@gmail.com>
BREAKING CHANGE: If your config has a `admin.components.routes` array, you will need to key them into the `admin.components.views` object. The configuration options should remain unchanged.
* chore: WIP id type validation for richtext upload
* chore: fix richtext fields test ID placeholder replacements
* chore: use getIDType in relationship validation for consistency
* chore: make getIDType safer in case payload.db.defaultIDType is null
---------
Co-authored-by: Dan Ribbens <dan.ribbens@gmail.com>
BREAKING: config (SanitizedConfig) is now a new, mandatory property to be passed into .validate(, options) functions. In order to accommodate that, other functions which may call validate now also have a new, mandatory config property. These are:
* buildStateFromSchema
* addFieldStatePromise
feat: breaking: richtext-lexical: block node validations
* ci: cache entire build to share with future jobs
* chore: pnpm setup for tests job
* chore: use build cache in db adapter builds
* chore: troubleshoot db builds
* chore: add back db-mongodb
* chore: add back db-postgres, cleanup
* chore: separate type gen into separate job
* chore: run tests separately for each db adapter
* chore: use matrix for tests w/ db
* chore: explicit ip and port for postgres
* chore: exportPointerFiles script
* chore: handle creation of subfolders which may not exist
* chore: add json to copyfiles
* chore: do not use exports property for publishConfig
* chore: add clean:unix command
* chore: modify clean:unix command to also delete any tsconfig.tsbuildinfo files
* chore: remove exports properties from db adapter packages
* chore: cleanup tsconfigs and fix db-mongodb builds
* chore: make the db adapters depend on payload
* chore: fix tsconfig for test directory
* chore: fix packages/db-mongodb not building
BREAKING CHANGE:
- Unhandled Errors are now omitted by default. This can be breaking if people depend on those error messages. Now, it will just say "Something went wrong.".
* chore: slightly improved testing of registration via graphql
Signed-off-by: Vsevolod Volkov <st.lyn4@gmail.com>
* chore: hiding details of internal errors from responses
Signed-off-by: Vsevolod Volkov <st.lyn4@gmail.com>
* feat: ability to remove authorization tokens from response bodies
Signed-off-by: Vsevolod Volkov <st.lyn4@gmail.com>
* chore: add section for design contributions in contributing.md
* feat: add afterOperation hook (#2697)
* feat: add afterOperation hook for Find operation
* docs: change #afterOperation to #afteroperation
* chore: extract afterOperation in function
* chore: implement afterChange in operations
* docs: use proper CollectionAfterOperationHook
* chore: remove outdated info
* chore: types afterOperation hook
* chore: improves afterOperation tests
* docs: updates description of afterOperation hook
* chore: improve typings
* chore: improve types
* chore: rename index.tsx => index.ts
---------
Co-authored-by: Jacob Fletcher <jacobsfletch@gmail.com>
Co-authored-by: Alessio Gravili <alessio@gravili.de>
* chore: remove swc version pin (#3179)
* fix: WhereBuilder component does not accept all valid Where queries (#3087)
* chore: add jsDocs for ListControls
* chore: add jsDocs for ListView
* chore: add jsDocs for WhereBuilder
* chore: add comment
* chore: remove unnecessary console log
* chore: improve operator type
* fix: transform where queries which aren't necessarily incorrect, and improve their validation
* chore: add type to import
* fix: do not merge existing old query params with new ones if the existing old ones got transformed and are not valid, as that would cause duplicates
* chore: sort imports and remove extra validation
* fix: transformWhereQuery logic
* chore: add back extra validation
* chore: add e2e tests
* chore(test): adds test to ensure relationship returns over 10 docs (#3181)
* chore(test): adds test to ensure relationship returns over 10 docs
* chore: remove unnecessary movieDocs variable
* fix: passes in height to resizeOptions upload option to allow height resize (#3171)
* docs: fixes syntax error in rich-text.mdx that was breaking build
* docs: removes auto-formatting from rich-text.mdx (#3188)
* feat: Improve admin dashboard accessibility (#3053)
Co-authored-by: Alessio Gravili <alessio@gravili.de>
* feat: improve field ops (#3172)
Co-authored-by: PatrikKozak <patrik@trbl.design>
* chore: file cleanup (#3190)
* chore(release): v1.14.0
* chore: improve ts typing in sanitization functions (#3194)
* chore(templates): default port on website
* chore(templates): safely handles bad network requests
* chore(templates): implements draft preview and on-demand revalidation
* chore(templates): renders static cart page fallback
* chore(examples): updates draft-preview next-app example to use revalidateTag (#3199)
* feat: query support for geo within and intersects + dynamic GraphQL operator types (#3183)
Co-authored-by: Lucas Blancas <lablancas@gmail.com>
* chore: improve checkboxes (#3191)
* chore: improve filtering for hasMany number field (#3193)
* chore: improve fiiltering for hasMany number field
* chore: add translation for 'items' and replace rows with items
* chore: new exceededLimit key
* Revert "chore: add translation for 'items' and replace rows with items"
This reverts commit 3a91dabdfd.
* chore: undo adding items key in translation schema
* chore: new limitReached key
* chore: remove unnecessary exceededLimit key
* chore: spelling improvements
* chore: update test build config import
---------
Signed-off-by: Vsevolod Volkov <st.lyn4@gmail.com>
Co-authored-by: Vsevolod Volkov <st.lyn4@gmail.com>
Co-authored-by: Jarrod Flesch <30633324+JarrodMFlesch@users.noreply.github.com>
Co-authored-by: Alessio Gravili <alessio@gravili.de>
Co-authored-by: ibr-hin95 <ibr.hin95@gmail.com>
Co-authored-by: Seied Ali Mirkarimi <dasmergo@gmail.com>
Co-authored-by: muathkhatib <mkhatib.dev@gmail.com>
Co-authored-by: ibr-hin95 <40246707+ibr-hin95@users.noreply.github.com>
fix: recursiveNestedPaths not merging existing fields when hoisting row/collapsible fields (#2769)
fix: exclude monaco code editor from ltr due to microsoft/monaco-editor#2371
BREAKING CHANGE:
- The admin hook for `useLocale` now returns a Locale object of the currently active locale. Previously this would only return the code as a string. Any custom components built which had `locale = useLocale()` should be replaced with `{ code: locale } = useLocale()` to maintain the same functionality.
- The property `localization.locales` of `SanitizedConfig` type has changed. This was an array of strings and is now an array of Locale objects having: `label: string`, `code: string` and `rtl: boolean`. If you are using localization.locales from the config you will need to adjust your project or plugin accordingly.
* chore: disable slug pluralization for versions model
* chore: disable slug pluralizations for globals version model
* chore: disable auto slug pluralization for globals collection
* feat: autoPluralization option for mongoose adapter
* Update isActive.tsx
This change allows us to define toggling of custom types in Slate. Specifically, this fixes the ability to toggle Alignment on nodes that use other active elements.
isElementActive(editor, format, TEXT_ALIGN_TYPES.includes(format) ? 'align' : 'type');
Type is the default for elements, allowing us to use a custom field lets us greater extend the functionality of Slate in Payload without causing any breaking changes
* Update toggle.tsx
Added to toggleElement public function
* Update isActive.tsx
* Update toggle.tsx
Added Rich Text Alignment, updated toggle function, added tests and doc updates
* added margin to void elements
* fix: list alignment
* removed textAlign from elements and added docs
* chore: fix typo
---------
Co-authored-by: Alessio Gravili <alessio@gravili.de>
* feat: make PAYLOAD_CONFIG_PATH optional
* hardcode common search paths
* docs: update docs regarding PAYLOAD_CONFIG_PATH
* make the tsConfig parser less prone to errors
* feat(ImageResize): add support for resize options
* fix(ImageUpload): reuse name for accidental duplicate
* fix(ImageResize): e2e tests for added media size
* chore: simplify fileExists method
* fix: typo
* feat(ImageResize): update name to be more transparent
* fix: use fileExists in file removal
* improve names, comments and clarity of needsResize function
* fix: jsDoc params
* fix: incorrect needsResize condition and add failing test case
* chore: improve comment
* fix: merge conflict error
---------
Co-authored-by: Alessio Gravili <70709113+AlessioGr@users.noreply.github.com>
* chore: add jsDocs for buildQuery
* feat: where instead of id for updateOne and deleteOne
* feat: find => findOne
* sort order => sort direction
* fix: typing of Global buildQuery
* cleanup
* fix: init payload's i18n for error message
* fix: incorrect use of FindArgs in findByID
* move deleteOne call to adapter
* re-order
* deleteVersions
* versions stuff
* more version stuff
* moar version stuff
* global stuff
* global stuff
* move combineQueries inside the findGlobal
* global stuff
* fix type
* more global stuff
* move docWithFilenameExists to adapter pattern
* chore: remove unnecessary comments
* perf: make everything lean, disable virtuals, ++performance
* chore: remove unnecessary Model
* chore: add jsdocs for limit
* moar jsdocs
* Replace find in deleteByID
* (check this:) add missing locale
* move findByID
* Make findByID return only one document
* _id => id
* _id => id
* Improve version types
* Improve sortOrder types
* move version stuff over
* version stuff
* fix: sort types
* fix params
* fix: findVersionByID generic
* fix: type error for versions
* remove unused value
* fix: Document import
* add todo
* feat: updateOne to mongoose
* remove unnecessary Model
* more update stuff
* remove unnecessary imports
* remove unnecessary function arguments
* fix: auth db update calls
* fix: bad updateByID which made tests fail
* fix: update returned docs to fix tests
* fix: update from version using mongoose directly even though the Model does not exist
* feat: implement deleteOne
* fix: assign verificationToken only when it exists - fixes test
* migrate saveVersion partly
* feat: make dev:generate-graphql-schema work even without specifying extra argument
* fix: this.db can be null
* chore: use destructured locale where possible
* chore: improve variable name
* fix: SanitizedConfig type
* feat: findGlobal database adapter
* fix: flaky e2e test
* chore: improve incorrect comment
* chore: undo diffs
* fix: id types
* fix: id typing
Specified that you don't need to provide any credentials when using a correct IAM Role. IAM Roles are recommended by AWS over direct credentials due to superior security.
without default value, it gives error in payload admin page (in console of browser)
caught SyntaxError: "undefined" is not valid JSON
at JSON.parse (<anonymous>)
at ./src/payload.config.ts
as envs are not availabe in payload admin GCS_CREDENTIALS gives undefined
resulting JSON.parse(undefined) raises this error
* added custom config extension points
* Added custom field to documentation
* fix: not building due to incorrect typings
* Upload dist
* point to number array test
* feat: hasMany for number field
* fix: types
* Fix: incorrectly styles input for hasMany
* Revert "point to number array test"
This reverts commit 5a5162a803.
* Revert "Merge branch 'production-with-custom' into number-hasmany-v2"
This reverts commit dfc3ac523e, reversing
changes made to a3b1b7dd67.
* test: adds test for numbers with hasMany
* test: add number field e2e
* Fix updated index.tsx
* Fix updated index.tsx
* chore: add jsDocs for hasMany property
* chore: rename isMultiText to isCreatable, as it makes more sense
* fix: incorrect double space in comments
* chore: rename onMultiTextChange to handleHasManyChange
* chore: improve ordering
* docs: add documentation for hasMany
* docs: add more jsdocs for number field
* fix: new value not transformed to number
* improve types
* fix: only allow numbers as input using filterOption
* fix: Option / value type breaking sortable selects
* fix: typings and add id for sorting
* add animation to react select
* undo transitions due to glitches
* fix: keyboard handler for select for empty input values
* fix: validation for hasMany numbers
* feat: perform validation in the filter as well
* attempt to fix duplicate key issue
* add todo
* remove console logs
* fix: stupid key warning
* fix: validation tests
* feat: add filterOption to keydown listener
* feat: numberOnly for react-select
* chore: improve variable naming
* fix: allow numbers for relationship value by stringifying those for sortable react-selects
* feat: generated types for hasMany number field
* graphql typings part 1
* graphql defaults type
* better typing for number in buildObjectType
* fix: default graphql type disregarding hasMany for relationship field
* feat: minRows and maxRows for hasMany numbers
* simplify joi schema
* working minRows and maxRows validation!
* jesus christ: fix incorrect translations for number & relationship fields for greaterThanMax and lessThanMin
* fix weird type error
* move validation tests to validations.spec.ts and fix them
* fix: make sure filterOption only passes a number array to validate function
* fix: adds missing dark-mode styles for version differences view (#2812)
Co-authored-by: Tylan Davis <tylan@Tylans-MacBook-Pro.local>
* fix: #2821 i18n ui field label (#2823)
* chore: version diff styles (#2824)
Co-authored-by: Tylan Davis <tylan@Tylans-MacBook-Pro.local>
* chore: remove --legacy-peer-deps from gh actions workflow (#2814)
* chore: removes cms text from instances of payload name (#2793)
* chore(release): v1.9.2
* chore: update changelog release notes v1.9.2
* chore: cleans up graphql-schema-gen test folder
* fix: adds custom property to ui field in joi validation (#2835)
* adjust validation
* improve isnumber function
* Update number.mdx
---------
Co-authored-by: Teun Mooij <tmooij@infinitaslearning.com>
Co-authored-by: Dan Ribbens <dan.ribbens@gmail.com>
Co-authored-by: Tylan Davis <89618855+tylandavis@users.noreply.github.com>
Co-authored-by: Tylan Davis <tylan@Tylans-MacBook-Pro.local>
Co-authored-by: Dan Ribbens <DanRibbens@users.noreply.github.com>
Co-authored-by: Jacob Fletcher <jacobsfletch@gmail.com>
Co-authored-by: Jarrod Flesch <jarrodmflesch@gmail.com>
Co-authored-by: Jarrod Flesch <30633324+JarrodMFlesch@users.noreply.github.com>
* fix: deprecate min/max in exchange for minRows and maxRows for relationship
* fix: update validations unit tests with minRows and maxRows
* fix: incorrect types
* move to sanitize
**BREAKING CHANGES**
Preferences have been overhauled to be abstracted as a Payload collection and no longer explicitly defined by Payload. They previously used the slug `_preferences` as a collection name and url route and are now
If any of the following are true you will need to take action:
- You have existing preferences you wish to keep for your admin users you must migrate data in the _preferences collection to the new shape. To migrate the preferences in the database you must update the shape of each _preferences document from:
```js
{
user: ObjectId("abc"),
userCollection: "users",
/** other fields remain the same **/
}
```
to:
```js
{
user: {
value: 'abc',
relationTo: 'users",
}
/** other fields remain the same **/
}
```
- You have code external of Payload or custom code within Payload using the API endpoint `api/_preferences`, you should update any applications to use `api/payload-preferences` instead.
- You were using the preferences GraphQL implementation. This was removed and is instead provided the same way as Payload handles any other. In this way the queries, mutation and schemas have changed. These are now generated as any other collection within your payload project.
- You were using the Payload's exported Preference type for your typescript code. Now you can instead import the generated type from your project.
* chore: colocates gql schema field types with operators
* chore: adds missing `json` gql field schema
* fix: corrects graphql `id` type from JSON to String
* Add paginatedType to graphQL on collections types
* Refactor config query and mutation extension into a reusable type
* Export paginatedListType and payload's version of graphql
* Revert prettier's automatic changes
* Fix requested changes
* Add additional documentation for extending GraphQL
* Add information about the resolver's first argument
* Refactor imageResizer.ts to allow for keeping original size in certain cases
* revert new property for keeping desired size
* add unit tests for maintained image size feature
* feat: support full URL for upload.staticURL
* feat: Update documentation about upload.staticURL property
* feat: Add reproduction test for absolute staticURL
* chore: ensures example configs are being exported when necessary
* chore: adds note regarding updating of hidden fields
---------
Co-authored-by: Jessica Boezwinkle <jessica@trbl.design>
* feat: support email configuration in payload config
* feat: set email defaults if no email config
* chore: leftover line from testing
* feat: add warning if email configure in both init and config
* chore: use correct locale when querying relationship for list view
* chore: make sure the relationships are re-queried when the locale changes
* chore: cleans up localization test ts-types
---------
Co-authored-by: Jarrod Flesch <jarrodmflesch@gmail.com>
Fixes ERROR (payload): TypeError: Cannot read properties of undefined (reading '<field.name>')
at promise (...\payload\src\fields\hooks\afterChange\promise.ts:68:23)
at ...\payload\src\fields\hooks\afterChange\traverseFields.ts:31:26
at Array.forEach (<anonymous>)
at traverseFields (...\payload\src\fields\hooks\afterChange\traverseFields.ts:30:10)
at promise (...\payload\src\fields\hooks\afterChange\promise.ts:154:27)
at ...\payload\src\fields\hooks\afterChange\traverseFields.ts:31:26
at Array.forEach (<anonymous>)
at traverseFields (...\payload\src\fields\hooks\afterChange\traverseFields.ts:30:10)
at promise (...\payload\src\fields\hooks\afterChange\promise.ts:170:27)
at ...\payload\src\fields\hooks\afterChange\traverseFields.ts:31:26
*Note:* Feature requests should be opened as [discussions](https://github.com/payloadcms/payload/discussions/new?category=feature-requests-ideas).
- type:input
id:reproduction-link
attributes:
label:Link to reproduction
description:Want us to look into your issue faster? Follow the [reproduction-guide](https://github.com/payloadcms/payload/blob/main/.github/reproduction-guide.md) for more information.
validations:
required:false
- type:textarea
attributes:
label:Describe the Bug
validations:
required:true
- type:textarea
attributes:
label:To Reproduce
description:Steps to reproduce the behavior, please provide a clear description of how to reproduce the issue, based on the linked minimal reproduction. Screenshots can be provided in the issue body below. If using code blocks, make sure that [syntax highlighting is correct](https://docs.github.com/en/get-started/writing-on-github/working-with-advanced-formatting/creating-and-highlighting-code-blocks#syntax-highlighting) and double check that the rendered preview is not broken.
validations:
required:true
- type:input
id:version
attributes:
label:Payload Version
description:What version of Payload are you running?
validations:
required:true
- type:input
id:adapters-plugins
attributes:
label:Adapters and Plugins
description:What adapters and plugins are you using? ie. db-mongodb, db-postgres, bundler-webpack, etc.
- type:markdown
attributes:
value:Before submitting the issue, go through the steps you've written down to make sure the steps provided are detailed and clear.
- type:markdown
attributes:
value:Contributors should be able to follow the steps provided in order to reproduce the bug.
- type:markdown
attributes:
value:These steps are used to add integration tests to ensure the same issue does not happen again. Thanks in advance!
1. [Fork](https://github.com/payloadcms/payload/fork) this repo
2. Optionally, create a new branch for your reproduction
3. Run `pnpm install` to install dependencies
4. Open up the `test/_community` directory
5. Add any necessary `collections/globals/fields` in this directory to recreate the issue you are experiencing
6. Run `pnpm dev _community` to start the admin panel
**NOTE:** The goal is to isolate the problem by reducing the number of `collections/globals/fields` you add to the `test/_community` folder. This folder is _not_ meant for you to copy your project into, but rather recreate the issue you are experiencing with minimal config.
## Example test directory file tree
```text
.
├── config.ts
├── int.spec.ts
├── e2e.spec.ts
└── payload-types.ts
```
-`config.ts` - This is the _granular_ Payload config for testing. It should be as lightweight as possible. Reference existing configs for an example
-`int.spec.ts` [Optional] - This is the test file run by jest. Any test file must have a `*int.spec.ts` suffix.
-`e2e.spec.ts` [Optional] - This is the end-to-end test file that will load up the admin UI using the above config and run Playwright tests.
-`payload-types.ts` - Generated types from `config.ts`. Generate this file by running `pnpm dev:generate-types _community`.
The directory split up in this way specifically to reduce friction when creating tests and to add the ability to boot up Payload with that specific config. You should modify the files in `test/_community` to get started.
<br />
## Testing is optional but encouraged
An issue does not need to have failing tests — reproduction steps with your forked repo are enough at this point. Some people like to dive deeper and we want to give you the guidance/tools to do so. Read more below:
### Running integration tests (Payload API tests)
First install [Jest Runner for VSVode](https://marketplace.visualstudio.com/items?itemName=firsttris.vscode-jest-runner).
There are a couple ways run integration tests:
- **Granularly** - you can run individual tests in vscode by installing the Jest Runner plugin and using that to run individual tests. Clicking the `debug` button will run the test in debug mode allowing you to set break points.
Once they are installed you can open the `testing` tab in vscode sidebar and drill down to the test you want to run, i.e. `/test/_community/e2e.spec.ts`
The default credentials are `dev@payloadcms.com` as email and `test` as password. They can be found in `test/credentials.ts`. By default, these will be autofilled, so no log-in is required.
<configurationdefault="false"name="Run Dev Fields"type="NodeJSConfigurationType"application-parameters="fields"path-to-js-file="node_modules/.pnpm/nodemon@3.0.3/node_modules/nodemon/bin/nodemon.js"working-dir="$PROJECT_DIR$">
<configurationdefault="false"name="Run Dev _community"type="NodeJSConfigurationType"application-parameters="_community"path-to-js-file="node_modules/.pnpm/nodemon@3.0.3/node_modules/nodemon/bin/nodemon.js"working-dir="$PROJECT_DIR$">
node-linker=isolated # due to a typescript bug, isolated mode requires @types/express-serve-static-core, terser and monaco-editor to be installed https://github.com/microsoft/TypeScript/issues/47663#issuecomment-1519138189 along with two other changes in the code which I've marked with (tsbugisolatedmode) in the code
Below you'll find a set of guidelines for how to contribute to Payload.
## Opening issues
Before you submit an issue, please check all existing [open and closed issues](https://github.com/payloadcms/payload/issues) to see if your issue has previously been resolved or is already known. If there is already an issue logged, feel free to upvote it by adding a :thumbsup: [reaction](https://github.com/blog/2119-add-reactions-to-pull-requests-issues-and-comments). If you would like to submit a new issue, please fill out our Issue Template to the best of your ability so we can accurately understand your report.
## Security issues & vulnerabilities
If you come across an issue related to security, or a potential attack vector within Payload or one of its dependencies, please DO NOT create a publicly viewable issue. Instead, please contact us directly at [`dev@payloadcms.com`](mailto:dev@payloadcms.com). We will do everything we can to respond to the issue as soon as possible.
If you find a vulnerability within the core Payload repository, and we determine that it is remediable and of significant nature, we will be happy to pay you a reward for your findings and diligence. [`Contact us`](mailto:dev@payloadcms.com) to find out more.
## Documentation edits
Payload documentation can be found directly within its codebase, and you can feel free to make changes / improvements to any of it through opening a PR. We utilize these files directly in our website and will periodically deploy documentation updates as necessary.
## Building additional features
If you're an incredibly awesome person and want to help us make Payload even better through new features or additions, we would be thrilled to work with you.
## Design Contributions
When it comes to design-related changes or additions, it's crucial for us to ensure a cohesive user experience and alignment with our broader design vision. Before embarking on any implementation that would affect the design or UI/UX, we ask that you **first share your design proposal** with us for review and approval.
Our design review ensures that proposed changes fit seamlessly with other components, both existing and planned. This step is meant to prevent unintentional design inconsistencies and to save you from investing time in implementing features that might need significant design alterations later.
### Before Starting
To help us work on new features, you can create a new feature request post in [GitHub Discussion](https://github.com/payloadcms/payload/discussions) or discuss it in our [Discord](https://discord.com/invite/payload). New functionality often has large implications across the entire Payload repo, so it is best to discuss the architecture and approach before starting work on a pull request.
### Installation & Requirements
Payload is structured as a Monorepo, encompassing not only the core Payload platform but also various plugins and packages. To install all required dependencies, you have to run `pnpm install` once in the root directory. **PNPM IS REQUIRED!** Yarn or npm will not work - you will have to use pnpm to develop in the core repository. In most systems, the easiest way to install pnpm is to run `corepack enable` in your terminal.
If you're coming from a very outdated version of payload, it is recommended to nuke the node_modules folder before running pnpm install. On UNIX systems, you can easily do that using the `pnpm clean:unix` command, which will delete all node_modules folders and build artefacts.
It is also recommended to use at least Node v18 or higher. You can check your current node version by typing `node --version` in your terminal. The easiest way to switch between different node versions is to use [nvm](https://github.com/nvm-sh/nvm#intro).
### Code
Most new functionality should keep testing in mind. All top-level directories within the `test/` directory are for testing a specific category: `fields`, `collections`, etc.
If it makes sense to add your feature to an existing test directory, please do so.
A typical directory with `test/` will be structured like this:
```text
.
├── config.ts
├── int.spec.ts
├── e2e.spec.ts
└── payload-types.ts
```
-`config.ts` - This is the _granular_ Payload config for testing. It should be as lightweight as possible. Reference existing configs for an example
-`int.spec.ts` - This is the test file run by jest. Any test file must have a `*int.spec.ts` suffix.
-`e2e.spec.ts` - This is the end-to-end test file that will load up the admin UI using the above config and run Playwright tests. These tests are typically only needed if a large change is being made to the Admin UI.
-`payload-types.ts` - Generated types from `config.ts`. Generate this file by running `pnpm dev:generate-types my-test-dir`. Replace `my-test-dir` with the name of your testing directory.
Each test directory is split up in this way specifically to reduce friction when creating tests and to add the ability to boot up Payload with that specific config.
The following command will start Payload with your config: `pnpm dev my-test-dir`. Example: `pnpm dev fields` for the test/`fields` test suite. This command will start up Payload using your config and refresh a test database on every restart. If you're using VS Code, the most common run configs are automatically added to your editor - you should be able to find them in your VS Code launch tab.
By default, payload will [automatically log you in](https://payloadcms.com/docs/authentication/config#admin-autologin) with the default credentials. To disable that, you can either pass in the --no-auto-login flag (example: `pnpm dev my-test-dir --no-auto-login`) or set the `PAYLOAD_PUBLIC_DISABLE_AUTO_LOGIN` environment variable to `false`.
The default credentials are `dev@payloadcms.com` as E-Mail and `test` as password. These are used in the auto-login.
### Testing with your own MongoDB database
If you wish to use your own MongoDB database for the `test` directory instead of using the in memory database, all you need to do is add the following env vars to the `test/dev.ts` file:
-`process.env.NODE_ENV`
-`process.env.PAYLOAD_TEST_MONGO_URL`
- Simply set `process.env.NODE_ENV` to `test` and set `process.env.PAYLOAD_TEST_MONGO_URL` to your MongoDB URL e.g. `mongodb://127.0.0.1/your-test-db`.
### Using Postgres
If you have postgres installed on your system, you can also run the test suites using postgres. By default, mongodb is used.
To do that, simply set the `PAYLOAD_DATABASE` environment variable to `postgres`.
### Running the e2e and int tests
You can run the entire test suite using `pnpm test`. If you wish to only run e2e tests, you can use `pnpm test:e2e`. If you wish to only run int tests, you can use `pnpm test:int`.
By default, `pnpm test:int` will only run int test against MongoDB. To run int tests against postgres, you can use `pnpm test:int:postgres`. You will have to have postgres installed on your system for this to work.
### Commits
We use [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/) for our commit messages. Please follow this format when creating commits. Here are some examples:
-`feat: adds new feature`
-`fix: fixes bug`
-`docs: adds documentation`
-`chore: does chore`
Here's a breakdown of the format. At the top-level, we use the following types to categorize our commits:
-`feat`: new feature that adds functionality. These are automatically added to the changelog when creating new releases.
-`fix`: a fix to an existing feature. These are automatically added to the changelog when creating new releases.
-`docs`: changes to [docs](./docs) only. These do not appear in the changelog.
-`chore`: changes to code that is neither a fix nor a feature (e.g. refactoring, adding tests, etc.). These do not appear in the changelog.
If you are committing to [templates](./templates) or [examples](./examples), use the `chore` type with the proper scope, like this:
-`chore(templates): adds feature to template`
-`chore(examples): fixes bug in example`
## Pull Requests
For all Pull Requests, you should be extremely descriptive about both your problem and proposed solution. If there are any affected open or closed issues, please leave the issue number in your PR message.
## Previewing docs
This is how you can preview changes you made locally to the docs:
3. Duplicate the `.env.example` file and rename it to `.env`
4. Add a `DOCS_DIR` environment variable to the `.env` file which points to the absolute path of your modified docs folder. For example `DOCS_DIR=/Users/yourname/Documents/GitHub/payload/docs`
5. Run `yarn run fetchDocs:local`. If this was successful, you should see no error messages and the following output: *Docs successfully written to /.../website/src/app/docs.json*. There could be error messages if you have incorrect markdown in your local docs folder. In this case, it will tell you how you can fix it
6. You're done! Now you can start the website locally using `yarn run dev` and preview the docs under [http://localhost:3000/docs/](http://localhost:3000/docs/)
To report an issue, please follow the steps below:
1. Fork this repository
2. Add necessary collections/globals/fields to the `test/_community` directory to recreate the issue you are experiencing
3. Create an issue and add a link to your forked repo
**The goal is to isolate the problem by reducing the number of fields/collections you add to the test/\_community folder. This folder is not meant for you to copy your project into, but to recreate the issue you are experiencing with minimal config.**
## Test directory file tree explanation
```text
.
├── config.ts
├── int.spec.ts
├── e2e.spec.ts
└── payload-types.ts
```
-`config.ts` - This is the _granular_ Payload config for testing. It should be as lightweight as possible. Reference existing configs for an example
-`int.spec.ts` [Optional] - This is the test file run by jest. Any test file must have a `*int.spec.ts` suffix.
-`e2e.spec.ts` [Optional] - This is the end-to-end test file that will load up the admin UI using the above config and run Playwright tests.
-`payload-types.ts` - Generated types from `config.ts`. Generate this file by running `pnpm dev:generate-types _community`.
The directory split up in this way specifically to reduce friction when creating tests and to add the ability to boot up Payload with that specific config. You should modify the files in `test/_community` to get started.
## How to start test collection admin UI
To start the admin panel so you can manually recreate your issue, you can run the following command:
```bash
# This command will start up Payload using your config
# NOTE: it will wipe the test database on restart
pnpm dev _community
```
## Testing is optional but encouraged
An issue does not need to have failing tests — reproduction steps with your forked repo are enough at this point. Some people like to dive deeper and we want to give you the guidance/tools to do so. Read more below.
### How to run integration tests (Payload API tests)
There are a couple ways to do this:
- **Granularly** - you can run individual tests in vscode by installing the Jest Runner plugin and using that to run individual tests. Clicking the `debug` button will run the test in debug mode allowing you to set break points.
Once they are installed you can open the `testing` tab in vscode sidebar and drill down to the test you want to run, i.e. `/test/_community/e2e.spec.ts`
- It is recommended to add the test credentials (located in `test/credentials.ts`) to your autofill for `localhost:3000/admin` as this will be required on every nodemon restart. The default credentials are `dev@payloadcms.com` as email and `test` as password.
<h3 align="center">The most powerful TypeScript CMS</h3>
<p align="center">Code-first Headless CMS that bridges the gap between CMS and application framework</p>
> [!IMPORTANT]
> 🎉 <strong>Payload 3.0 beta released!</strong> You can now deploy Payload fully in any Next.js app folder. Read more in the <a target="_blank" href="https://payloadcms.com/blog/30-beta-install-payload-into-any-nextjs-app-with-one-line" rel="dofollow"><strong>announcement post</strong></a>.
<h3 align="center">
<a target="_blank" href="https://payloadcms.com/docs/getting-started/what-is-payload" rel="dofollow"><strong>Explore the docs</strong></a>
·
<a target="_blank" href="https://demo.payloadcms.com/" rel="dofollow"><strong>Try Live Demo</strong></a>
<br />
</h3>
<h3>Benefits over a regular CMS</h3>
<ul>
<li>Don’t hit some third-party SaaS API, hit your own API</li>
<li>Use your own database and own your data</li>
<li>It's just Express - do what you want outside of Payload</li>
<li>No need to learn how Payload works - if you know JS, you know Payload</li>
<li>No vendor lock-in</li>
<li>Avoid microservices hell - get everything (even auth) in one place</li>
<li>Never touch ancient WP code again</li>
<li>Build faster, never hit a roadblock</li>
<li>Both admin and backend are 100% extensible</li>
Create a cloud account, connect your GitHub, and [deploy in minutes](https://payloadcms.com/new).
<br />
## 🚀 Get started by self-hosting completely free, forever.
<a href="https://payloadcms.com">
<img src="https://cms.payloadcms.com/media/payload-github-header.jpg" alt="Payload headless CMS Admin panel built with React" />
</a>
Before beginning to work with Payload, make sure you have all of the [required software](https://payloadcms.com/docs/getting-started/installation).
<br />
```text
npx create-payload-app@latest
```
## ⭐ Why Payload?
Alternatively, it only takes about five minutes to [create an app from scratch](https://payloadcms.com/docs/getting-started/installation#from-scratch).
Payload is a CMS that has been designed for developers from the ground up to deliver them what they need to build great digital products. If you know JavaScript, you know Payload. It's a _code-first_ CMS, which allows us to do a lot of things right:
## 🖱️ One-click templates
- Payload gives you everything you need, but then steps back and lets you build what you want in JavaScript or TypeScript - with no unnecessary complexity brought by GUIs. You'll understand how your CMS works because you will have written it exactly how you want it.
- Bring your own Express server and do whatever you need on top of Payload. Payload doesn't impose anything on you or your app.
- Completely control the Admin panel by using your own React components. Swap out fields or even entire views with ease.
- Use your data however and wherever you need thanks to auto-generated, yet fully extensible REST, GraphQL, and Local Node APIs.
Jumpstart your next project by starting with a pre-made template. These are production-ready, end-to-end solutions designed to get you to market as fast as possible.
<a target="_blank" href="https://payloadcms.com/" rel="dofollow"><strong>Read more on our website</strong></a>
Eliminate the need to combine Shopify and a CMS, and instead do it all with Payload + Stripe. Comes with a beautiful, fully functional front-end complete with shopping cart, checkout, orders, and much more.
Build any kind of website, blog, or portfolio from small to enterprise. Comes with a beautiful, fully functional front-end complete with posts, projects, comments, and much more.
We're constantly adding more templates to our [Templates Directory](https://github.com/payloadcms/payload/tree/main/templates). If you maintain your own template, consider adding the `payload-template` topic to your GitHub repository for others to find.
Before beginning to work with Payload, make sure you have all of the [required software](https://payloadcms.com/docs/getting-started/installation).
From there, the easiest way to get started with Payload is to use the `create-payload-app` package:
```text
npx create-payload-app
```
Alternatively, it only takes about five minutes to [create an app from scratch](https://payloadcms.com/docs/getting-started/installation#from-scratch).
## 🗒️ Documentation
Check out the [Payload website](https://payloadcms.com/docs/getting-started/what-is-payload) to find in-depth documentation for everything that Payload offers.
Migrating from v1 to v2? Check out the [2.0 Release Notes](https://github.com/payloadcms/payload/releases/tag/v2.0.0) on how to do it.
## 🙋 Contributing
If you want to add contributions to this repository, please follow the instructions in [contributing.md](./contributing.md).
If you want to add contributions to this repository, please follow the instructions in [contributing.md](./CONTRIBUTING.md).
## 📚 Examples
The [Examples Directory](./examples) is a great resource for learning how to setup Payload in a variety of different ways, but you can also find great examples in our blog and throughout our social media.
Payload is highly extensible and allows you to install or distribute plugins that add or remove functionality. There are both officially-supported and community-supported plugins available. If you maintain your own plugin, consider adding the `payload-plugin` topic to your GitHub repository for others to find.
There are lots of good conversations and resources in our Github Discussions board & our Discord Server. If you're struggling with something, chances are, someone's already solved what you're up against. :point_down:
There are lots of good conversations and resources in our Github Discussions board and our Discord Server. If you're struggling with something, chances are, someone's already solved what you're up against. :point_down:
Below you'll find a set of guidelines for how to contribute to Payload CMS.
## Opening issues
Before you submit an issue, please check all existing [open and closed issues](https://github.com/payloadcms/payload/issues) to see if your issue has previously been resolved or is already known. If there is already an issue logged, feel free to upvote it by adding a :thumbsup: [reaction](https://github.com/blog/2119-add-reactions-to-pull-requests-issues-and-comments). If you would like to submit a new issue, please fill out our Issue Template to the best of your ability so we can accurately understand your report.
## Security issues & vulnerabilities
If you come across an issue related to security, or a potential attack vector within Payload or one of its dependencies, please DO NOT create a publicly viewable issue. Instead, please contact us directly at [`dev@payloadcms.com`](mailto:dev@payloadcms.com). We will do everything we can to respond to the issue as soon as possible.
If you find a vulnerability within the core Payload repository, and we determine that it is remediable and of significant nature, we will be happy to pay you a reward for your findings and diligence. [`Contact us`](mailto:dev@payloadcms.com) to find out more.
## Documentation edits
Payload documentation can be found directly within its codebase and you can feel free to make changes / improvements to any of it through opening a PR. We utilize these files directly in our website and will periodically deploy documentation updates as necessary.
## Building additional features
If you're an incredibly awesome person and want to help us make Payload even better through new features or additions, we would be thrilled to work with you.
### Before Starting
To help us work on new features, you can create a new feature request post in [GitHub Discussion](https://github.com/payloadcms/payload/discussions) or discuss it in our [Discord](https://discord.com/invite/r6sCXqVk3v). New functionality often has large implications across the entire Payload repo, so it is best to discuss the architecture and approach before starting work on a pull request.
### Code
Most new functionality should keep testing in mind. With 1.0, testability of new features has been vastly improved. All top-level directories within the `test/` directory are for testing a specific category: `fields`, `collections`, etc.
If it makes sense to add your feature to an existing test directory, please do so.
A typical directory with `test/` will be structured like this:
```text
.
├── config.ts
├── int.spec.ts
├── e2e.spec.ts
└── payload-types.ts
```
-`config.ts` - This is the _granular_ Payload config for testing. It should be as lightweight as possible. Reference existing configs for an example
-`int.spec.ts` - This is the test file run by jest. Any test file must have a `*int.spec.ts` suffix.
-`e2e.spec.ts` - This is the end-to-end test file that will load up the admin UI using the above config and run Playwright tests. These tests are typically only needed if a large change is being made to the Admin UI.
-`payload-types.ts` - Generated types from `config.ts`. Generate this file by running `yarn dev:generate-types my-test-dir`.
The directory split up in this way specifically to reduce friction when creating tests and to add the ability to boot up Payload with that specific config.
The following command will start Payload with your config: `yarn dev my-test-dir`. This command will start up Payload using your config and refresh a test database on every restart.
When switching between test directories, you will want to remove your `node_modules/.cache ` manually or by running `yarn clean:cache`.
NOTE: It is recommended to add the test credentials (located in `test/credentials.ts`) to your autofill for `localhost:3000/admin` as this will be required on every nodemon restart. The default credentials are `dev@payloadcms.com` as E-Mail and `test` as password.
## Pull Requests
For all Pull Requests, you should be extremely descriptive about both your problem and proposed solution. If there are any affected open or closed issues, please leave the issue number in your PR message.
| **`req`** | The Express `request` object containing the currently authenticated `user` |
| **`id`** | `id` of the document being read |
| **`doc`** | The full document data. |
| **`siblingData`** | Immediately adjacent field data of the document being read. |
| **`id`** | `id` of the document being read |
| **`doc`** | The full document data. |
| **`siblingData`** | Immediately adjacent field data of the document being read. |
### Update
Returns a boolean which allows or denies the ability to update a field's value. If `false` is returned, any passed values will be discarded.
If `false` is returned and you attempt to update the field's value, the operation will **not** throw an error however the field will be omitted from the update operation and the value will remain unchanged.
Access control within Payload is extremely powerful while remaining easy and intuitive to manage. Declaring who should have access to what documents is no more complex than writing a simple JavaScript function that either returns a `boolean` or a [`query`](/docs/queries/overview) constraint to restrict which documents users can interact with.
<YouTube
id="DoPLyXG26Dg"
title="Overview of Payload Access Control"
/>
<YouTube id="DoPLyXG26Dg" title="Overview of Payload Access Control" />
**Example use cases:**
@@ -32,13 +29,18 @@ Access control within Payload is extremely powerful while remaining easy and int
In the Local API, all Access Control functions are skipped by default, allowing your server to do whatever it needs. But, you can opt back in by setting the option <strong>overrideAccess</strong> to <strong>true</strong>.
<strong>Note:</strong>
<br />
In the Local API, all Access Control functions are skipped by default, allowing your server to do
whatever it needs. But, you can opt back in by setting the option <strong>
overrideAccess
</strong>{' '}
to <strong>false</strong>.
</Banner>
### Access Control Types
@@ -49,12 +51,13 @@ You can manage access within Payload on three different levels:
- [Fields](/docs/access-control/fields)
- [Globals](/docs/access-control/globals)
### When Access Control is Executed
<Banner type="success">
<strong>Note:</strong><br/>
Access control functions are utilized in two places. It's important to understand how and when your access control is executed.
<strong>Note:</strong>
<br />
Access control functions are utilized in two places. It's important to understand how and when
your access control is executed.
</Banner>
#### As you execute operations
@@ -70,8 +73,11 @@ To accomplish this, Payload ships with an `Access` operation, which is executed
### Argument Availability
<Banner type="warning">
<strong>Important:</strong><br/>
When your access control functions are executed via the <strong>access</strong> operation, the <strong>id</strong> and <strong>data</strong> arguments will be <strong>undefined</strong>, because Payload is executing your functions without referencing a specific document.
<strong>Important:</strong>
<br />
When your access control functions are executed via the <strong>access</strong> operation, the{' '}
<strong>id</strong> and <strong>data</strong> arguments will be <strong>undefined</strong>,
because Payload is executing your functions without referencing a specific document.
</Banner>
If you use `id` or `data` within your access control functions, make sure to check that they are defined first. If they are not, then you can assume that your access control is being executed via the `access` operation, to determine solely what the user can do within the Admin UI.
desc: Bundlers are used to bundle the code that serves Payload's Admin Panel.
---
Payload has two official bundlers, the [Webpack Bundler](/docs/admin/webpack) and the [Vite Bundler](/docs/admin/vite). You must install a bundler to use the admin panel.
##### Install a bundler
Webpack (recommended):
```text
yarn add @payloadcms/bundler-webpack
```
Vite (beta):
```text
yarn add @payloadcms/bundler-vite
```
##### Configure the bundler
```ts
// payload.config.ts
import { buildConfig } from 'payload/config'
import { webpackBundler } from '@payloadcms/bundler-webpack'
// import { viteBundler } from '@payloadcms/bundler-vite'
export default buildConfig({
// highlight-start
admin: {
bundler: webpackBundler() // or viteBundler()
},
// highlight-end
})
```
### What are bundlers?
At their core, a bundler's main goal is to take a bunch of files and turn them into a few optimized files that you ship to the browser. The admin UI has a root `index.html` entry point, and from there the bundler traverses the dependency tree, bundling all of the files that are required from that point on.
Since the bundled file is sent to the browser, it can't include any server-only code. You will need to remove any server-only code from your admin UI before bundling it. You can learn more about [excluding server code](/docs/admin/excluding-server-code) section.
<Banner type="warning">
<strong>Using environment variables in the admin UI</strong>
<br />
Bundles should not contain sensitive information. By default, Payload
excludes env variables from the bundle. If you need to use env variables in your payload config,
you need to prefix them with `PAYLOAD_PUBLIC_` to make them available to the client-side code.
While designing the Payload Admin panel, we determined it should be as minimal and straightforward as possible to allow easy customization and control. There are many times where you may want to completely control how a whole view or a field works. You might even want to add in your own routes entirely. In order for Payload to support that level of customization without introducing versioning / future-proofing issues, Payload provides for a pattern to supply your own React components via your Payload config.
While designing the Payload Admin panel, we determined it should be as minimal and straightforward as possible to allow easy customization and control. There are many times where you may want to completely control how a whole view or a field works. You might even want to add in new views entirely. In order for Payload to support this level of customization without introducing versioning / future-proofing issues, Payload provides for a pattern to supply your own React components via your Payload config.
To swap in your own React component, first, consult the list of available component overrides below. Determine the scope that corresponds to what you are trying to accomplish, and then author your React component accordingly.
<Banner type="success">
<strong>Tip:</strong>
<br />
Custom components will automatically be provided with all props that the
default component would accept.
Custom components will automatically be provided with all props that the default component normally
accepts.
</Banner>
### Base Component Overrides
You can override a set of admin panel-wide components by providing a component to your base Payload config's `admin.components` property. The following options are available:
| **`Nav`** | Contains the sidebar and mobile Nav in its entirety. |
| **`logout.Button`** | A custom React component.
| **`BeforeDashboard`** | Array of components to inject into the built-in Dashboard, _before_ the default dashboard contents. |
| **`AfterDashboard`** | Array of components to inject into the built-in Dashboard, _after_ the default dashboard contents. [Demo](https://github.com/payloadcms/payload/tree/master/test/admin/components/AfterDashboard/index.tsx) |
| **`BeforeLogin`** | Array of components to inject into the built-in Login, _before_ the default login form. |
| **`AfterLogin`** | Array of components to inject into the built-in Login, _after_ the default login form. |
| **`BeforeNavLinks`** | Array of components to inject into the built-in Nav, _before_ the links themselves. |
| **`AfterNavLinks`** | Array of components to inject into the built-in Nav, _after_ the links. |
| **`views.Account`** | The Account view is used to show the currently logged in user's Account page. |
| **`views.Dashboard`** | The main landing page of the Admin panel. |
| **`graphics.Icon`** | Used as a graphic within the `Nav` component. Often represents a condensed version of a full logo. |
| **`graphics.Logo`** | The full logo to be used in contexts like the `Login` view. |
| **`routes`** | Define your own routes to add to the Payload Admin UI. [More](#custom-routes) |
| **`providers`** | Define your own provider components that will wrap the Payload Admin UI. [More](#custom-providers) |
| **`Nav`** | Contains the sidebar / mobile menu in its entirety. |
| **`BeforeNavLinks`** | Array of components to inject into the built-in Nav, _before_ the links themselves. |
| **`AfterNavLinks`** | Array of components to inject into the built-in Nav, _after_ the links. |
| **`BeforeDashboard`** | Array of components to inject into the built-in Dashboard, _before_ the default dashboard contents. |
| **`AfterDashboard`** | Array of components to inject into the built-in Dashboard, _after_ the default dashboard contents. [Demo](https://github.com/payloadcms/payload/tree/main/test/admin/components/AfterDashboard/index.tsx) |
| **`BeforeLogin`** | Array of components to inject into the built-in Login, _before_ the default login form. |
| **`AfterLogin`** | Array of components to inject into the built-in Login, _after_ the default login form. |
| **`logout.Button`** | A custom React component. |
| **`graphics.Icon`** | Used as a graphic within the `Nav` component. Often represents a condensed version of a full logo. |
| **`graphics.Logo`** | The full logo to be used in contexts like the `Login` view. |
| **`providers`** | Define your own provider components that will wrap the Payload Admin UI. [More](#custom-providers) |
| **`actions`** | Array of custom components to be rendered in the Payload Admin UI header, providing additional interactivity and functionality. |
| **`views`** | Override or create new views within the Payload Admin UI. [More](#views) |
#### Full example:
Here is a full example showing how to swap some of these components for your own.
`payload.config.js`
```ts
import { buildConfig } from "payload/config";
import { buildConfig } from 'payload/config'
import {
MyCustomNav,
MyCustomLogo,
@@ -51,7 +51,8 @@ import {
MyCustomAccount,
MyCustomDashboard,
MyProvider,
} from "./customComponents";
MyCustomAdminAction,
} from './customComponents'
export default buildConfig({
admin: {
@@ -61,6 +62,7 @@ export default buildConfig({
Icon: MyCustomIcon,
Logo: MyCustomLogo,
},
actions: [MyCustomAdminAction],
views: {
Account: MyCustomAccount,
Dashboard: MyCustomDashboard,
@@ -68,27 +70,401 @@ export default buildConfig({
providers: [MyProvider],
},
},
});
})
```
_For more examples regarding how to customize components, look at the following [examples](https://github.com/payloadcms/payload/tree/master/test/admin/components)._
#### Views
You can easily swap entire views with your own by using the `admin.components.views` property. At the root level, Payload renders the following views by default, all of which can be overridden:
| **`Account`** | The Account view is used to show the currently logged in user's Account page. |
| **`Dashboard`** | The main landing page of the Admin panel. |
To swap out any of these views, simply pass in your custom component to the `admin.components.views` property of your Payload config. For example:
```ts
// payload.config.ts
{
// ...
admin: {
components: {
views: {
Account: MyCustomAccountView,
Dashboard: MyCustomDashboardView,
},
},
},
}
```
For more granular control, pass a configuration object instead. Each view corresponds to its own `<Route />` component in [React Router v5](https://v5.reactrouter.com). Payload exposes all of the properties of React Router:
_\* An asterisk denotes that a property is required._
#### Adding new views
To add a _new_ view to the Admin Panel, simply add another key to the `views` object with at least a `path` and `Component` property. For example:
```ts
// payload.config.ts
{
// ...
admin: {
components: {
views: {
MyCustomView: {
Component: MyCustomView,
path: '/my-custom-view',
},
},
},
},
}
```
<Banner type="warning">
<strong>Note:</strong>
<br />
Routes are cascading. This means that unless explicitly given the `exact` property, they will match on URLs that simply _start_ with the route's path. This is helpful when creating catch-all routes in your application. Alternatively, you could define your nested route _before_ your parent route.
</Banner>
_For more examples regarding how to customize components, look at the following [examples](https://github.com/payloadcms/payload/tree/main/test/admin/components)._
For help on how to build your own custom view components, see [building a custom view component](#building-a-custom-view-component).
### Collections
You can override components on a Collection-by-Collection basis via each Collection's `admin` property.
You can override components on a collection-by-collection basis via the `admin.components` property.
| **`BeforeList`** | Array of components to inject _before_ the built-in List view |
| **`BeforeListTable`** | Array of components to inject _before_ the built-in List view's table |
| **`AfterList`** | Array of components to inject _after_ the built-in List view |
| **`AfterListTable`** | Array of components to inject _after_ the built-in List view's table |
| **`edit.SaveButton`** | Replace the default `Save` button with a custom component. Drafts must be disabled |
| **`edit.SaveDraftButton`** | Replace the default `Save Draft` button with a custom component. Drafts must be enabled and autosave must be disabled. |
| **`edit.PublishButton`** | Replace the default `Publish` button with a custom component. Drafts must be enabled. |
| **`edit.PreviewButton`** | Replace the default `Preview` button with a custom component. |
| **`views`** | Override or create new views within the Payload Admin UI. [More](#collection-views) |
Here is a full example showing how to swap some of these components for your own:
To swap out entire views on collections, you can use the `admin.components.views` property on the collection's config. Payload renders the following views by default, all of which can be overridden:
| **`Edit`** | The Edit view is used to edit a single document for a given collection. |
| **`List`** | The List view is used to show a list of documents for a given collection. |
To swap out any of these views, simply pass in your custom component to the `admin.components.views` property of your Payload config. This will replace the entire view, including the page breadcrumbs, title, tabs, etc, _as well as all nested routes_.
```ts
// Collection.ts
{
// ...
admin: {
components: {
views: {
Edit: MyCustomEditView,
List: MyCustomListView,
},
},
},
}
```
_For help on how to build your own custom view components, see [building a custom view component](#building-a-custom-view-component)._
**Customizing Nested Views within 'Edit' in Collections**
The `Edit` view in collections consists of several nested views, each serving a unique purpose. You can customize these nested views using the `admin.components.views.Edit` property in the collection's configuration. This approach allows you to replace specific nested views while keeping the overall structure of the `Edit` view intact, including the page breadcrumbs, title, tabs, etc.
Here's an example of how you can customize nested views within the `Edit` view in collections, including the use of the `actions` property:
```ts
// Collection.ts
{
// ...
admin: {
components: {
views: {
Edit: {
Default: {
Component: MyCustomDefaultTab,
actions: [CollectionEditButton], // Custom actions for the default edit view
},
API: {
Component: MyCustomAPIView,
actions: [CollectionAPIButton], // Custom actions for API view
},
LivePreview: {
Component: MyCustomLivePreviewView,
actions: [CollectionLivePreviewButton], // Custom actions for Live Preview
},
Version: {
Component: MyCustomVersionView,
actions: [CollectionVersionButton], // Custom actions for Version view
},
Versions: {
Component: MyCustomVersionsView,
actions: [CollectionVersionsButton], // Custom actions for Versions view
},
},
List: {
actions: [CollectionListButton],
},
},
},
},
}
```
**Adding New Tabs to 'Edit' View**
You can also add _new_ tabs to the `Edit` view by adding another key to the `components.views.Edit[key]` object with a `path` and `Component` property. See [Custom Tabs](#custom-tabs) for more information.
### Globals
As with Collections, You can override components on a global-by-global basis via their `admin` property.
As with Collections, you can override components on a global-by-global basis via the `admin.components` property.
| **`elements.SaveButton`** | Replace the default `Save` button with a custom component. Drafts must be disabled |
| **`elements.SaveDraftButton`** | Replace the default `Save Draft` button with a custom component. Drafts must be enabled and autosave must be disabled. |
| **`elements.PublishButton`** | Replace the default `Publish` button with a custom component. Drafts must be enabled. |
| **`elements.PreviewButton`** | Replace the default `Preview` button with a custom component. |
| **`views`** | Override or create new views within the Payload Admin UI. [More](#global-views) |
#### Global views
To swap out views for globals, you can use the `admin.components.views` property on the global's config. Payload renders the following views by default, all of which can be overridden:
| **`Edit`** | The Edit view is used to edit a single document for a given Global. |
To swap out any of these views, simply pass in your custom component to the `admin.components.views` property of your Payload config. This will replace the entire view, including the page breadcrumbs, title, and tabs, _as well as all nested views_.
```ts
// Global.ts
{
// ...
admin: {
components: {
views: {
Edit: MyCustomEditView,
},
},
},
}
```
_For help on how to build your own custom view components, see [building a custom view component](#building-a-custom-view-component)._
**Customizing Nested Views within 'Edit' in Globals**
Similar to collections, Globals allow for detailed customization within the `Edit` view. This includes the ability to swap specific nested views while maintaining the overall structure of the `Edit` view. You can use the `admin.components.views.Edit` property in the Globals configuration to achieve this, and this will only replace the nested view, leaving the page breadcrumbs, title, and tabs intact.
Here's how you can customize nested views within the `Edit` view in Globals, including the use of the `actions` property:
```ts
// Global.ts
{
// ...
admin: {
components: {
views: {
Edit: {
Default: {
Component: MyCustomGlobalDefaultTab,
actions: [GlobalEditButton], // Custom actions for the default edit view
},
API: {
Component: MyCustomGlobalAPIView,
actions: [GlobalAPIButton], // Custom actions for API view
},
LivePreview: {
Component: MyCustomGlobalLivePreviewView,
actions: [GlobalLivePreviewButton], // Custom actions for Live Preview
},
Version: {
Component: MyCustomGlobalVersionView,
actions: [GlobalVersionButton], // Custom actions for Version view
},
Versions: {
Component: MyCustomGlobalVersionsView,
actions: [GlobalVersionsButton], // Custom actions for Versions view
},
},
},
},
},
}
```
You can also add _new_ tabs to the `Edit` view by adding another key to the `components.views.Edit[key]` object with a `path` and `Component` property. See [Custom Tabs](#custom-tabs) for more information.
### Custom Tabs
You can easily swap individual collection or global edit views. To do this, pass an _object_ to the `admin.components.views.Edit` property of the config. Payload renders the following views by default, all of which can be overridden:
Edit: { // You can also define `components.views.Edit` as a component, this will override _all_ nested views
Default: MyCustomDefaultTab,
Versions: MyCustomVersionsTab,
Version: MyCustomVersionTab,
API: MyCustomAPITab,
LivePreview: MyCustomLivePreviewTab,
},
},
},
},
}
```
To add a _new_ tab to the `Edit` view, simply add another key to `components.views.Edit[key]` with at least a `path` and `Component` property. For example:
| **`user`** | The currently logged in user. Will be `null` if no user is logged in. |
| **`canAccessAdmin`** \* | If the currently logged in user is allowed to access the admin panel or not. |
<Banner type="warning">
<strong>Note:</strong>
<br />
It's up to you to secure your custom views. If your view requires a user to be logged in or to
have certain access rights, you should handle that within your view component yourself.
</Banner>
#### Example
You can find examples of custom views in the [Payload source code `/test/admin/components/views` folder](https://github.com/payloadcms/payload/tree/main/test/admin/components/views). There, you'll find two custom views:
1. A custom view that uses the `DefaultTemplate`, which is the built-in Payload template that displays the sidebar and "eyebrow nav"
1. A custom view that uses the `MinimalTemplate` - which is just a centered template used for things like logging in or out
To see how to pass in your custom views to create custom views of your own, take a look at the `admin.components.views` property of the [Payload test admin config](https://github.com/payloadcms/payload/blob/main/test/admin/config.ts).
### Fields
@@ -97,10 +473,9 @@ All Payload fields support the ability to swap in your own React components. So,
<Banner type="success">
<strong>Tip:</strong>
<br />
Don't see a built-in field type that you need? Build it! Using a combination
of custom validation and custom components, you can override the entirety of
how a component functions within the admin panel and effectively create your
own field type.
Don't see a built-in field type that you need? Build it! Using a combination of custom validation
and custom components, you can override the entirety of how a component functions within the admin
panel and effectively create your own field type.
</Banner>
**Fields support the following custom components:**
@@ -111,6 +486,15 @@ All Payload fields support the ability to swap in your own React components. So,
| **`Cell`** | Used in the `List` view's table to represent a table-based preview of the data stored in the field. [More](#cell-component) |
| **`Field`** | Swap out the field itself within all `Edit` views. [More](#field-component) |
As an alternative to replacing the entire Field component, you may want to keep the majority of the default Field component and only swap components within. This allows you to replace the **`Label`** or **`Error`** within a field component or add additional components inside the field with **`beforeInput`** or **`afterInput`**. **`beforeInput`** and **`afterInput`** are allowed in any fields that don't contain other fields, except [UI](/docs/fields/ui) and [Rich Text](/docs/fields/rich-text).
@@ -146,80 +532,132 @@ When writing your own custom components you can make use of a number of hooks to
When swapping out the `Field` component, you'll be responsible for sending and receiving the field's `value` from the form itself. To do so, import the `useField` hook as follows:
```tsx
import { useField } from "payload/components/forms";
import { useField } from 'payload/components/forms'
For more information regarding the hooks that are available to you while you
build custom components, including the <strong>useField</strong> hook, <a href="/docs/admin/hooks" style={{ color: "black" }}>click here</a>.
For more information regarding the hooks that are available to you while you build custom
components, including the <strong>useField</strong> hook, [click here](/docs/admin/hooks).
</Banner>
## Custom routes
## Label Component
You can easily add your own custom routes to the Payload Admin panel using the `admin.components.routes` property. Payload currently uses the extremely powerful React Router v5.x and custom routes support all the properties of the React Router `<Route />` component.
These are the props that will be passed to your custom Label.
**Custom routes support the following properties:**
| **`htmlFor`** | Property used to set `for` attribute for label. |
| **`label`** | Label value provided in field, it can be used with i18n. |
| **`required`** | A boolean value that represents if the field is required or not. |
#### Example
You can find examples of custom route views in the [Payload source code `/test/admin/components/views` folder](https://github.com/payloadcms/payload/tree/master/test/admin/components/views). There, you'll find two custom routes:
```tsx
import React from 'react'
import { useTranslation } from 'react-i18next'
1. A custom view that uses the `DefaultTemplate`, which is the built-in Payload template that displays the sidebar and "eyebrow nav"
1. A custom view that uses the `MinimalTemplate` - which is just a centered template used for things like logging in or out
import { getTranslation } from 'payload/utilities/getTranslation'
To see how to pass in your custom views to create custom routes of your own, take a look at the `admin.components.routes` property of the [Payload test admin config](https://github.com/payloadcms/payload/blob/master/test/admin/config.ts).
| **`showError`** | A boolean value that represents if the error should be shown. |
#### Example
```tsx
import React from 'react'
type Props = {
message: string
showError?: boolean
}
const CustomError: React.FC<Props> = (props) => {
const { message, showError } = props
if (showError) {
return <p style={{color: 'red'}}>{message}</p>
} else return null;
}
```
## afterInput and beforeInput
With these properties you can add multiple components before and after the input element. For example, you can add an absolutely positioned button to clear the current field value.
As your admin customizations gets more complex you may want to share state between fields or other components. You can add custom providers to do add your own context to any Payload app for use in other custom components within the admin panel. Within your config add `admin.components.providers`, these can be used to share context or provide other custom functionality. Read the [React context](https://reactjs.org/docs/context.html) docs to learn more.
<Banner type="warning">
<strong>Reminder:</strong> Don't forget to pass the **children** prop through
the provider component for the admin UI to show
<strong>Reminder:</strong> Don't forget to pass the **children** prop through the provider
component for the admin UI to show
</Banner>
### Styling Custom Components
Payload exports its SCSS variables and mixins for reuse in your own custom components. This is helpful in cases where you might want to style a custom input similarly to Payload's built-ini styling, so it blends more thoroughly into the existing admin UI.
Payload exports its SCSS variables and mixins for reuse in your own custom components. This is helpful in cases where you might want to style a custom input similarly to Payload's built-in styling, so it blends more thoroughly into the existing admin UI.
To make use of Payload SCSS variables / mixins to use directly in your own components, you can import them as follows:
@@ -232,41 +670,42 @@ To make use of Payload SCSS variables / mixins to use directly in your own compo
When developing custom components you can support multiple languages to be consistent with Payload's i18n support. The best way to do this is to add your translation resources to the [i18n configuration](https://payloadcms.com/docs/configuration/i18n) and import `useTranslation` from `react-i18next` in your components.
In any custom component you can get the selected locale with the `useLocale` hook. Here is a simple example:
In any custom component you can get the selected locale with `useLocale` hook. `useLocale` returns the full locale object, consisting of a `label`, `rtl`(right-to-left) property, and then `code`. Here is a simple example:
```tsx
import { useLocale } from "payload/components/utilities";
import { useLocale } from 'payload/components/utilities'
@@ -30,7 +31,7 @@ To make it as easy as possible for you to override our styles, Payload uses [BEM
In addition to adding your own style definitions, you can also override Payload's built-in CSS variables. We use as much as possible behind the scenes, and you can override any of them that you'd like to.
You can find the built-in Payload CSS variables within [`./src/admin/scss/app.scss`](https://github.com/payloadcms/payload/blob/master/src/admin/scss/app.scss) and [`./src/admin/scss/colors.scss`](https://github.com/payloadcms/payload/blob/master/src/admin/scss/colors.scss). The following variables are defined and can be overridden:
You can find the built-in Payload CSS variables within [`./src/admin/scss/app.scss`](https://github.com/payloadcms/payload/blob/main/packages/payload/src/admin/scss/app.scss) and [`./src/admin/scss/colors.scss`](https://github.com/payloadcms/payload/blob/main/packages/payload/src/admin/scss/colors.scss). The following variables are defined and can be overridden:
- Breakpoints
- Base color shades (white to black by default)
@@ -43,7 +44,8 @@ You can find the built-in Payload CSS variables within [`./src/admin/scss/app.sc
#### Dark mode
<Banner type="warning">
If you're overriding colors or theme elevations, make sure to consider how your changes will affect dark mode.
If you're overriding colors or theme elevations, make sure to consider how your changes will
affect dark mode.
</Banner>
By default, Payload automatically overrides all `--theme-elevation`s and inverts all success / warning / error shades to suit dark mode. We also update some base theme variables like `--theme-bg`, `--theme-text`, etc.
This key will automatically be made available to the Payload bundle and can be referenced in your Admin component code as `process.env.PAYLOAD_PUBLIC_STRIPE_PUBLISHABLE_KEY`.
desc: Learn how to exclude server-only code from the Payload Admin UI bundle
---
Because the Admin Panel browser bundle includes your Payload Config file, files using server-only modules need to be excluded.
It's common for your config to rely on server only modules to perform logic in access control functions, hooks, and other contexts.
Any file that imports a server-only module such as `fs`, `stripe`, `authorizenet`, `nodemailer`, etc. **cannot** be included in the browser bundle.
#### Example Scenario
Say we have a collection called `Subscriptions` that has a `beforeChange` hook that creates a Stripe subscription whenever a Subscription document is created in Payload.
**Collection config**:
```ts
// collections/Subscriptions/index.ts
import { CollectionConfig } from 'payload/types'
import createStripeSubscription from './hooks/createStripeSubscription'
The above code is NOT production-ready and should not be referenced to create Stripe
subscriptions. Although creating a beforeChange hook is a completely valid spot to do things like
create subscriptions, the code above is incomplete and insecure, meant for explanation purposes
only.
</Banner>
**As-is, this collection will prevent your Admin panel from bundling or loading correctly, because Stripe relies on some Node-only packages.**
#### How to fix this
You need to make sure that you use `alias`es to tell your bundler to import "safe" files vs. attempting to import any server-side code that you need to get rid of. Depending on your bundler (Webpack, Vite, etc.) the steps involved may be slightly different.
The basic idea is to create a file that exports an empty object, and then alias import paths of any files that import server-only modules to that empty object file.
This way when your bundler goes to import a file that contains server-only modules, it will instead import the empty object file, which will not break the browser bundle.
### Aliasing server-only modules
To remove files that contain server-only modules from your bundle, you can use an `alias`.
In the Subscriptions config file above, we are importing the hook like so:
```ts
// collections/Subscriptions/index.ts
import createStripeSubscription from './hooks/createStripeSubscription'
```
By default the browser bundle will now include all the code from that file and any files down the tree. We know that the file imports `stripe`.
To fix this, we need to alias the `createStripeSubscription` file to a different file that can safely be included in the browser bundle.
First, we will create a mock file to replace the server-only file when bundling:
```js
// mocks/modules.js
export default {}
/**
* NOTE: if you are destructuring an import
* the mock file will need to export matching
* variables as the destructured object.
*
* export const namedExport = {}
*/
```
Aliasing with [Webpack](/docs/admin/webpack) can be done by:
```ts
// payload.config.ts
import { buildConfig } from 'payload/config'
import { webpackBundler } from '@payloadcms/bundler-webpack'
import { Subscriptions } from './collections/Subscriptions'
There are times when a custom field component needs to have access to data from other fields, and you have a few options to do so. The `useFormFields` hook is a powerful and highly performant way to retrieve a form's field state, as well as to retrieve the `dispatchFields` method, which can be helpful for setting other fields' form states from anywhere within a form.
<Banner type="success">
<strong>This hook is great for retrieving only certain fields from form state</strong> because it ensures that it will only cause a rerender when the items that you ask for change.
<strong>This hook is great for retrieving only certain fields from form state</strong> because it
ensures that it will only cause a rerender when the items that you ask for change.
</Banner>
Thanks to the awesome package [`use-context-selector`](https://github.com/dai-shi/use-context-selector), you can retrieve a specific field's state easily. This is ideal because you can ensure you have an up-to-date field state, and your component will only re-render when _that field's state_ changes.
@@ -65,21 +66,19 @@ Thanks to the awesome package [`use-context-selector`](https://github.com/dai-sh
You can pass a Redux-like selector into the hook, which will ensure that you retrieve only the field that you want. The selector takes an argument with type of `[fields: Fields, dispatch: React.Dispatch<Action>]]`.
```tsx
import { useFormFields } from 'payload/components/forms';
import { useFormFields } from 'payload/components/forms'
const MyComponent: React.FC = () => {
// Get only the `amount` field state, and only cause a rerender when that field changes
| **`ADD_ROW`** | Adds a row of data (useful in array / block field data) |
| **`DUPLICATE_ROW`** | Duplicates a row of data (useful in array / block field data) |
| **`MODIFY_CONDITION`** | Updates a field's conditional logic result (true / false) |
@@ -127,46 +126,554 @@ You can send the following actions to the `dispatchFields` function.
| **`REPLACE_STATE`** | Completely replaces form state |
| **`UPDATE`** | Update any property of a specific field's state |
To see types for each action supported within the `dispatchFields` hook, check out the Form types [here](https://github.com/payloadcms/payload/blob/master/src/admin/components/forms/Form/types.ts).
To see types for each action supported within the `dispatchFields` hook, check out the Form types [here](https://github.com/payloadcms/payload/blob/main/packages/payload/src/admin/components/forms/Form/types.ts).
### useForm
The `useForm` hook can be used to interact with the form itself, and sends back many methods that can be used to reactively fetch form state without causing rerenders within your components each time a field is changed. This is useful if you have action-based callbacks that your components fire, and need to interact with form state _based on a user action_.
<Banner type="warning">
<strong>Warning:</strong><br/>
This hook is optimized to avoid causing rerenders when fields change, and as such, its `fields` property will be out of date. You should only leverage this hook if you need to perform actions against the form in response to your users' actions. Do not rely on its returned "fields" as being up-to-date. They will be removed from this hook's response in an upcoming version.
<strong>Warning:</strong>
<br />
This hook is optimized to avoid causing rerenders when fields change, and as such, its `fields`
property will be out of date. You should only leverage this hook if you need to perform actions
against the form in response to your users' actions. Do not rely on its returned "fields" as being
up-to-date. They will be removed from this hook's response in an upcoming version.
</Banner>
The `useForm` hook returns an object with the following properties:
The `useForm` hook returns an object with the following properties: |
In any custom component you can get the selected locale with the `useLocale` hook. Here is a simple example:
In any custom component you can get the selected locale object with the `useLocale` hook. `useLocale`gives you the full locale object, consisting of a `label`, `rtl`(right-to-left) property, and then `code`. Here is a simple example:
```tsx
import { useLocale } from 'payload/components/utilities';
import { useLocale } from 'payload/components/utilities'
const Greeting: React.FC = () => {
// highlight-start
const locale = useLocale();
const locale = useLocale()
// highlight-end
const trans = {
en: 'Hello',
es: 'Hola',
};
}
return (
<span> { trans[locale] } </span>
);
};
return <span> {trans[locale.code]} </span>
}
```
### useAuth
Useful to retrieve info about the currently logged in user as well as methods for interacting with it. It sends back an object with the following properties:
Sends back how many editing levels "deep" the current component is. Edit depth is relevant while adding new documents / editing documents in modal windows and other cases.
```tsx
import { useEditDepth } from 'payload/components/utilities';
import { useEditDepth } from 'payload/components/utilities'
const MyComponent: React.FC = () => {
// highlight-start
const editDepth = useEditDepth();
const editDepth = useEditDepth()
// highlight-end
return (
<span>My component is {editDepth} levels deep</span>
)
return <span>My component is {editDepth} levels deep</span>
}
```
### usePreferences
Returns methods to set and get user preferences. More info can be found [here](https://payloadcms.com/docs/admin/preferences).
### useTheme
Returns the currently selected theme (`light`, `dark` or `auto`), a set function to update it and a boolean `autoMode`, used to determine if the theme value should be set automatically based on the user's device preferences.
```tsx
import { useTheme } from 'payload/components/utilities'
const MyComponent: React.FC = () => {
// highlight-start
const { autoMode, setTheme, theme } = useTheme()
// highlight-end
return (
<>
<span>The current theme is {theme} and autoMode is {autoMode}</span>
The `useDocumentEvents` hook provides a way of subscribing to cross-document events, such as updates made to nested documents within a drawer. This hook will report document events that are outside the scope of the document currently being edited. This hook provides the following:
| **`mostRecentUpdate`** | An object containing the most recently updated document. It contains the `entitySlug`, `id` (if collection), and `updatedAt` properties |
| **`reportUpdate`** | A method used to report updates to documents. It accepts the same arguments as the `mostRecentUpdate` property. |
**Example:**
```tsx
import { useDocumentEvents } from 'payload/components/hooks'
const ListenForUpdates: React.FC = () => {
const { mostRecentUpdate } = useDocumentEvents()
return (
<span>
{JSON.stringify(mostRecentUpdate)}
</span>
)
}
```
<Banner type="info">
Right now the `useDocumentEvents` hook only tracks recently updated documents, but in the future it will track more document-related events as needed, such as document creation, deletion, etc.
Payload dynamically generates a beautiful, fully functional React admin panel to manage your data. It's extremely powerful and can be customized / extended upon easily by swapping in your own React components. You can add additional views, modify how built-in views look / work, swap out Payload branding for your client's, build your own field types and much more.
The Payload Admin panel is built with Webpack, code-split, highly performant (even with 100+ fields), and written fully in TypeScript.
The Payload Admin panel can be bundled with our officially supported [Vite](/docs/admin/vite) and [webpack](/docs/admin/webpack) bundlers or you can integrate another bundler following our adapter pattern approach.
When bundled, it is code-split, highly performant (even with 100+ fields), and written fully in TypeScript.
<Banner type="success">
The Admin panel is meant to be simple enough to give you a starting point but
not bring too much complexity, so that you can easily customize it to suit the
needs of your application and your editors.
The Admin panel is meant to be simple enough to give you a starting point but not bring too much
complexity, so that you can easily customize it to suit the needs of your application and your
editors.
</Banner>

_Screenshot of the Admin panel while editing a document from an example `AllFields` collection_
caption="Redesigned admin panel with a collapsible sidebar that's open by default, providing greater extensibility and enhanced horizontal real estate."
/>
## Admin Options
All options for the Admin panel are defined in your base Payload config file.
| `user` | The `slug` of a Collection that you want be used to log in to the Admin dashboard. [More](/docs/admin/overview#the-admin-user-collection) |
| `buildPath` | Specify an absolute path for where to store the built Admin panel bundle used in production. Defaults to `path.resolve(process.cwd(), 'build')`. |
| `meta` | Base meta data to use for the Admin panel. Included properties are `titleSuffix`, `ogImage`, and `favicon`. |
| `disable` | If set to `true`, the entire Admin panel will be disabled. |
| `indexHTML` | Optionally replace the entirety of the `index.html` file used by the Admin panel. Reference the [base index.html file](https://github.com/payloadcms/payload/blob/master/src/admin/index.html) to ensure your replacement has the appropriate HTML elements. |
| `css` | Absolute path to a stylesheet that you can use to override / customize the Admin panel styling. [More](/docs/admin/customizing-css). |
| `scss` | Absolute path to a Sass variables / mixins stylesheet meant to override Payload styles to make for an easy re-skinning of the Admin panel. [More](/docs/admin/customizing-css#overriding-scss-variables). |
| `dateFormat` | Global date format that will be used for all dates in the Admin panel. Any valid [date-fns](https://date-fns.org/) format pattern can be used. |
| `avatar` | Set account profile picture. Options: `gravatar`, `default` or a custom React component. |
| `components` | Component overrides that affect the entirety of the Admin panel. [More](/docs/admin/components) |
| `webpack` | Customize the Webpack config that's used to generate the Admin panel. [More](/docs/admin/webpack)| |
| **`logoutRoute`** | The route for the `logout` page. |
| **`inactivityRoute`** | The route for the `logout` inactivity page. |
| `bundler` | The bundler that you would like to use to bundle the admin panel. Officially supported bundlers: [Webpack](/docs/admin/webpack) and [Vite](/docs/admin/vite). |
| `user` | The `slug` of a Collection that you want be used to log in to the Admin dashboard. [More](/docs/admin/overview#the-admin-user-collection) |
| `buildPath` | Specify an absolute path for where to store the built Admin panel bundle used in production. Defaults to `path.resolve(process.cwd(), 'build')`. |
| `meta` | Base meta data to use for the Admin panel. Included properties are `titleSuffix`, `ogImage`, and `favicon`. |
| `disable` | If set to `true`, the entire Admin panel will be disabled. |
| `indexHTML` | Optionally replace the entirety of the `index.html` file used by the Admin panel. Reference the [base index.html file](https://github.com/payloadcms/payload/blob/main/packages/payload/src/admin/index.html) to ensure your replacement has the appropriate HTML elements. |
| `css` | Absolute path to a stylesheet that you can use to override / customize the Admin panel styling. [More](/docs/admin/customizing-css). |
| `scss` | Absolute path to a Sass variables / mixins stylesheet meant to override Payload styles to make for an easy re-skinning of the Admin panel. [More](/docs/admin/customizing-css#overriding-scss-variables). |
| `dateFormat` | Global date format that will be used for all dates in the Admin panel. Any valid [date-fns](https://date-fns.org/) format pattern can be used. |
| `avatar` | Set account profile picture. Options: `gravatar`, `default` or a custom React component. |
| `autoLogin` | Used to automate admin log-in for dev and demonstration convenience. [More](/docs/authentication/config). |
| `livePreview` | Enable real-time editing for instant visual feedback of your front-end application. [More](/docs/live-preview/overview). |
| `components` | Component overrides that affect the entirety of the Admin panel. [More](/docs/admin/components) |
| `webpack` | Customize the Webpack config that's used to generate the Admin panel. [More](/docs/admin/webpack) |
| `vite` | Customize the Vite config that's used to generate the Admin panel. [More](/docs/admin/vite) |
| `logoutRoute` | The route for the `logout` page. |
| `inactivityRoute` | The route for the `logout` inactivity page. |
### The Admin User Collection
<Banner type="warning">
<strong>Important:</strong>
<br />
The Payload Admin panel can only be used by one Collection that supports{" "}
The Payload Admin panel can only be used by one Collection that supports
[Authentication](/docs/authentication/overview).
</Banner>
To specify which Collection to use to log in to the Admin panel, pass the `admin` options a `user` key equal to the slug of the Collection that you'd like to use.
@@ -54,13 +62,13 @@ To specify which Collection to use to log in to the Admin panel, pass the `admin
`payload.config.js`:
```ts
import { buildConfig } from "payload/config";
import { buildConfig } from 'payload/config'
const config = buildConfig({
admin: {
user: "admins", // highlight-line
user: 'admins', // highlight-line
},
});
})
```
By default, if you have not specified a Collection, Payload will automatically provide you with a `User` Collection which will be used to access the Admin panel. You can customize or override the fields and settings of the default `User` Collection by passing your own collection using `users` as its `slug` to Payload. When this is done, Payload will use your provided `User` Collection instead of its default version.
@@ -15,8 +15,10 @@ Out of the box, Payload handles the persistence of your users' preferences in a
1. The "collapsed" state of blocks, on a document level, as users edit or interact with documents
<Banner type="warning">
<strong>Important:</strong><br/>
All preferences are stored on an individual user basis. Payload automatically recognizes the user that is reading or setting a preference via all provided authentication methods.
<strong>Important:</strong>
<br />
All preferences are stored on an individual user basis. Payload automatically recognizes the user
that is reading or setting a preference via all provided authentication methods.
</Banner>
### Use cases
@@ -30,17 +32,17 @@ This API is used significantly for internal operations of the Admin panel, as me
### Database
Payload automatically creates an internally used `_preferences` collection that stores user preferences. Each document in the `_preferences` collection contains the following shape:
Payload automatically creates an internally used `payload-preferences` collection that stores user preferences. Each document in the `payload-preferences` collection contains the following shape:
| Key | Value |
| -------------------- | -------------|
| `id` | A unique ID for each preference stored. |
| `key` | A unique `key` that corresponds to the preference. |
| `user` | The ID of the `user` that is storing its preference. |
| `userCollection` | The `slug` of the collection that the `user` is logged in as. |
| `value` | The value of the preference. Can be any data shape that you need. |
| `createdAt` | A timestamp of when the preference was created. |
| `updatedAt` | A timestamp set to the last time the preference was updated.
The Vite bundler is currently in beta. If you would like to help us test this package, we'd love to hear from you if you find any [bugs or issues](https://github.com/payloadcms/payload/issues/)!
</Banner>
Payload has a Vite bundler that you can install and bundle the Admin Panel with. This is an alternative to the [Webpack](/docs/admin/webpack) bundler and might give some performance boosts to your development workflow.
To use Vite as your bundler, first you need to install the package:
```bash
yarn add @payloadcms/bundler-vite
```
Then you will need to add the [bundler](/docs/admin/bundlers) to your Payload config:
```ts
import { buildConfig } from '@payloadcms/config'
import { viteBundler } from '@payloadcms/bundler-vite'
export default buildConfig({
collections: [],
admin: {
bundler: viteBundler(),
}
})
```
Vite works fundamentally differently than Webpack. In development mode, it will first pre-bundle any of your dependencies that are CommonJS-only, and then it'll leverage ESM directly in your browser for a better HMR experience.
It then uses Rollup to create production builds of your admin UI. With Vite, you should see a decent performance boost—especially after your first cold start. However, that first cold start might take a few more seconds.
<Banner type="warning">
In most cases, Vite should work out of the box. But existing Payload plugins may need to make compatibility changes to support Vite.
</Banner>
This is because Vite aliases work fundamentally differently than Webpack aliases, and Payload relies on aliasing server-only code out of the Payload config to ensure that the bundled admin JS works within your browser.
Here are the main differences between how Vite aliases work and how Webpack aliases work.
**Vite aliases do not work with absolute paths.**
In Vite, alias keys must <strong>exactly match</strong> a import paths. If you have 2 files that import the same server-only module, but have different import paths, you would need to add 2 aliases to support both import paths.
```ts
// File A
import serverOnlyModule from '../server-only-module'
// File B
import serverOnlyModule from '../../server-only-module'
// payload.config.ts
// You would need to add 2 aliases to support both import paths
**Vite aliases do not get applied to pre-bundled dependencies.**
This especially affects plugins, as plugins will be pre-bundled by Vite using `esbuild`. To get around this and support Vite, plugin authors need to configure an alias to their plugin at the top level, so that the alias will work accordingly.
Here's an example. Say your plugin is called `payload-plugin-cool`. It's imported as follows:
```ts
import { myCoolPlugin } from 'payload-plugin-cool'
```
That plugin should create an alias to support Vite as follows:
This will effectively alias the entire plugin and work with Vite. If the plugin requires admin-specific code, then the `./my-admin-plugin.js` alias target file should reflect any changes necessary to the admin UI that the main server-side plugin performs.
### Extending the Vite config
The Payload config supports a new property for plugins to be able to extend the Vite config specifically. That property exists on the main Payload config under `admin.vite`. You can check out the [Vite docs](https://vitejs.dev/config/shared-options.html) for more information on what you can do with the Vite config.
It's a function that takes a Vite config, and returns an updated Vite config. Here's an example:
Learn more about [aliasing server-only modules](https://payloadcms.com/docs/admin/excluding-server-code#aliasing-server-only-modules).
Even though there is a new property for Vite configs specifically, we have implemented some "compatibility" between Webpack and Vite out-of-the-box.
If your config specifies Webpack aliases, we attempt to leverage them automatically within the Vite config. They are merged into the Vite alias configuration seamlessly and may work out-of-the-box.
desc: The Payload admin panel uses Webpack 5 and supports many common functionalities such as SCSS and Typescript out of the box to give you more freedom.
Payload uses Webpack 5 to build the Admin panel. It comes with support for many common functionalities such as SCSS and Typescript out of the box, but there are many cases where you may need to add support for additional functionalities.
Payload has a Webpack (v5) bundler that you can build the Admin panel with. For now, we recommended using it because it is stable. If you are feeling a bit more adventurous you can give the [Vite](/docs/admin/vite) bundler a shot.
To extend the Webpack config, add the `webpack` key to your base Payload config, and provide a function that accepts the default Webpack config as its only argument:
Out of the box, the Webpack bundler supports common functionalities such as SCSS and Typescript, but there are many cases where you may need to add support for additional functionalities.
#### Installation
```bash
yarn add @payloadcms/bundler-webpack
```
#### Import the bundler
`payload.config.ts`
```ts
import { buildConfig } from 'payload/config';
// payload.config.ts
import { buildConfig } from 'payload/config'
import { webpackBundler } from '@payloadcms/bundler-webpack'
export default buildConfig({
admin: {
// highlight-start
webpack: (config) => {
// Do something with the config here
return config;
}
// highlight-end
}
});
// highlight-start
admin: {
bundler: webpackBundler()
},
// highlight-end
})
```
### Aliasing server-only modules
### Extending Webpack
A common use case for extending the Payload config is to alias server-only modules, thus preventing them from inclusion into the browser JavaScript bundle.
If you need to extend the Webpack config, you can do so by passing a function to the `admin.webpack` property on your Payload config.
The function will receive the Webpack config as an argument and should return the modified config.
As the Payload config is used in both server **and** client contexts, you may find yourself writing code in your Payload config that may be incompatible with browser environments.
Examples of **non** browser-friendly packages:
- `fs`
- `stripe`
- `authorizenet`
- `nodemailer`
You may rely on server-only packages such as the above to perform logic in access control functions, hooks, and other contexts (which is great!) but when you boot up your Payload app and try to view it in the browser, you'll likely run into missing dependency issues or other general incompatibilities.
<Banner type="success">
<strong>Tip:</strong><br/>
To avoid problems with server code making it to your Webpack bundle, you can use the <strong>alias</strong> Webpack feature to tell Webpack to avoid importing the modules you want to restrict to server-only.
</Banner>
<strong>For example, let's say that you have a Collection called `Subscriptions` which relies on Stripe:</strong>
<br/><br/>
`collections/Subscriptions/index.js`
```ts
import { CollectionConfig } from 'payload/types';
import createStripeSubscription from './hooks/createStripeSubscription';
// payload.config.ts
const Subscription: CollectionConfig = {
slug: 'subscriptions',
hooks: {
beforeChange: [
createStripeSubscription,
]
},
fields: [
{
name: 'stripeSubscriptionID',
type: 'text',
required: true,
}
]
};
export default Subscription;
```
The collection above features a `beforeChange` hook that creates a Stripe subscription whenever a Subscription document is created in Payload.
<strong>That hook might look something like this:</strong>
The above code is NOT production-ready and should not be referenced to create Stripe subscriptions. Although creating a beforeChange hook is a completely valid spot to do things like create subscriptions, the code above is incomplete and insecure, meant for explanation purposes only.
</Banner>
**As-is, this collection will prevent your Admin panel from bundling or loading correctly, because Stripe relies on some Node-only packages.**
To remedy this issue you can extend the Payload Webpack config to alias your entire `createStripeSubscription` hook to a separate, empty mock file.
Example in `payload.config.js`:
```js
import { buildConfig } from 'payload/config';
import path from 'path';
import Subscription from './collections/Subscription';
import { webpackBundler } from '@payloadcms/bundler-webpack'
export default buildConfig({
collections: [
Subscription
],
admin: {
webpack: (config) => ({
...config,
resolve: {
...config.resolve,
alias: {
...config.resolve.alias,
[createStripeSubscriptionPath]: mockModulePath,
}
}
})
}
});
admin: {
bundler: webpackBundler()
// highlight-start
webpack: (config) => {
// full control of the Webpackconfig
return config
},
// highlight-end
},
})
```
The above code will alias the file at path `createStripeSubscriptionPath` to a mocked module, which might look like this:
`mocks/emptyObject.js`
```js
export default {};
```
Now, when Webpack sees that you're attempting to import your `createStripeSubscriptionPath` file, it'll disregard that actual file and load your mock file instead. Not only will your Admin panel now bundle successfully, you will have optimized its filesize by removing unnecessary code! And you might have learned something about Webpack, too.
<Banner type="success">
<strong>Tip:</strong><br/>
If changes to your Webpack aliases are not surfacing, they might be [cached](https://webpack.js.org/configuration/cache/) in `node_modules/.cache/webpack`. Try deleting that folder and restarting your server.
<strong>Tip:</strong>
<br />
If changes to your Webpack aliases are not surfacing, they might be
[cached](https://webpack.js.org/configuration/cache/) in `node_modules/.cache/webpack`. Try
deleting that folder and restarting your server.
</Banner>
## Admin environment vars
<Banner type="warning">
<strong>Important:</strong><br />
Be careful about what variables you provide to your client-side code. Analyze every single one to make sure that you're not accidentally leaking anything that an attacker could exploit. Only keys that are safe to be available to everyone in plain text should be provided to your Admin panel.
</Banner>
By default, `env` variables are **not** provided to the Admin panel for security and safety reasons. But, Payload provides you with a way to still provide `env` vars to your frontend code.
**Payload will automatically supply any present `env` variables that are prefixed with `PAYLOAD_PUBLIC_` directly to the Admin panel.**
For example, if you've got the following environment variable:
This key will automatically be made available to the Payload bundle and can be referenced in your Admin component code as `process.env.PAYLOAD_PUBLIC_STRIPE_PUBLISHABLE_KEY`.
@@ -17,7 +17,7 @@ To enable Authentication on a collection, define an `auth` property and set it t
| **`useAPIKey`** | Payload Authentication provides for API keys to be set on each user within an Authentication-enabled Collection. [More](/docs/authentication/config#api-keys) |
| **`tokenExpiration`** | How long (in seconds) to keep the user logged in. JWTs and HTTP-only cookies will both expire at the same time. |
| **`maxLoginAttempts`** | Only allow a user to attempt logging in X amount of times. Automatically locks out a user from authenticating if this limit is passed. Set to `0` to disable. |
| **`lockTime`** | Set the time (in milliseconds) that a user should be locked out if they fail authentication more times than `maxLoginAttempts` allows for. |
| **`lockTime`** | Set the time (in milliseconds) that a user should be locked out if they fail authentication more times than `maxLoginAttempts` allows for. |
| **`depth`** | How many levels deep a `user` document should be populated when creating the JWT and binding the `user` to the express `req`. Defaults to `0` and should only be modified if absolutely necessary, as this will affect performance. |
| **`cookies`** | Set cookie options, including `secure`, `sameSite`, and `domain`. For advanced users. |
| **`forgotPassword`** | Customize the way that the `forgotPassword` operation functions. [More](/docs/authentication/config#forgot-password) |
@@ -29,34 +29,61 @@ To enable Authentication on a collection, define an `auth` property and set it t
To integrate with third-party APIs or services, you might need the ability to generate API keys that can be used to identify as a certain user within Payload.
In Payload, users are essentially documents within a collection. Just like you can authenticate as a user with an email and password, which is considered as our default local auth strategy, you can also authenticate as a user with an API key. API keys are generated on a user-by-user basis, similar to email and passwords, and are meant to represent a single user.
For example, if you have a third-party service or external app that needs to be able to perform protected actions at its discretion, you have two options:
1. Create a user for the third-party app, and log in each time to receive a token before you attempt to access any protected actions
1. Enable API key support for the Collection, where you can generate a non-expiring API key per user in the collection
1. Enable API key support for the Collection, where you can generate a non-expiring API key per user in the collection. This is particularly useful as you can create a "user" that reflects an integration with a specific external service and assign a "role" or specific access only needed by that service/integration. Alternatively, you could create a "super admin" user and assign an API key to that user so that any requests made with that API key are considered as being made by that super user.
Technically, both of these options will work for third-party integrations but the second option with API key is simpler, because it reduces the amount of work that your integrations need to do to be authenticated properly.
To enable API keys on a collection, set the `useAPIKey` auth option to `true`. From there, a new interface will appear in the Admin panel for each document within the collection that allows you to generate an API key for each user in the Collection.
<Banner type="success">
User API keys are encrypted within the database, meaning that if your database
is compromised, your API keys will not be.
User API keys are encrypted within the database, meaning that if your database is compromised,
your API keys will not be.
</Banner>
<Banner type="warning">
<strong>Important:</strong>
If you change your `PAYLOAD_SECRET`, you will need to regenerate your API keys.
<br />
The secret key is used to encrypt the API keys, so if you change the secret, existing API keys will no longer be valid.
</Banner>
#### Authenticating via API Key
To authenticate REST or GraphQL API requests using an API key, set the `Authorization` header. The header is case-sensitive and needs the slug of the `auth.useAPIKey` enabled collection, then " API-Key ", followed by the `apiKey` that has been assigned. Payload's built-in middleware will then assign the user document to `req.user` and handle requests with the proper access control.
To authenticate REST or GraphQL API requests using an API key, set the `Authorization` header. The header is case-sensitive and needs the slug of the `auth.useAPIKey` enabled collection, then " API-Key ", followed by the `apiKey` that has been assigned. Payload's built-in middleware will then assign the user document to `req.user` and handle requests with the proper access control. By doing this, Payload recognizes the request being made as a request by the user associated with that API key.
Payload ensures that the same, uniform access control is used across all authentication strategies. This enables you to utilize your existing access control configurations with both API keys and the standard email/password authentication. This consistency can aid in maintaining granular control over your API keys.
#### API Key _Only_ Authentication
If you want to use API keys as the only authentication method for a collection, you can disable the default local strategy by setting `disableLocalStrategy` to `true` on the collection's `auth` property. This will disable the ability to authenticate with email and password, and will only allow for authentication via API key.
```ts
import { CollectionConfig } from 'payload/types'
export const Customers: CollectionConfig = {
slug: 'customers',
auth: {
useAPIKey: true,
disableLocalStrategy: true,
},
}
```
### Forgot Password
@@ -70,26 +97,25 @@ Function that accepts one argument, containing `{ req, token, user }`, that allo
<Banner type="success">
<strong>Tip:</strong>
<br />
HTML templating can be used to create custom email templates, inline CSS
automatically, and more. You can make a reusable function that standardizes
all email sent from Payload, which makes sending custom emails more DRY.
Payload doesn't ship with an HTML templating engine, so you are free to choose
your own.
HTML templating can be used to create custom email templates, inline CSS automatically, and more.
You can make a reusable function that standardizes all email sent from Payload, which makes
sending custom emails more DRY. Payload doesn't ship with an HTML templating engine, so you are
free to choose your own.
</Banner>
Example:
```ts
import { CollectionConfig } from 'payload/types';
import { CollectionConfig } from 'payload/types'
const Customers: CollectionConfig = {
export const Customers: CollectionConfig = {
slug: 'customers',
auth: {
forgotPassword: {
// highlight-start
generateEmailHTML: ({ req, token, user }) => {
// Use the token provided to allow your user to reset their password
return `Hey ${user.email}, verify your email by clicking here: ${url}`;
}
return `Hey ${user.email}, verify your email by clicking here: ${url}`
},
// highlight-end
}
}
};
},
},
}
```
<Banner type="warning">
<strong>Important:</strong>
<br />
If you specify a different URL to send your users to for email verification,
such as a page on the frontend of your app or similar, you need to handle
making the call to the Payload REST or GraphQL verification operation yourself
on your frontend, using the token that was provided for you. Above, it was
passed via query parameter.
If you specify a different URL to send your users to for email verification, such as a page on the
frontend of your app or similar, you need to handle making the call to the Payload REST or GraphQL
verification operation yourself on your frontend, using the token that was provided for you.
Above, it was passed via query parameter.
</Banner>
**`generateEmailSubject`**
@@ -193,7 +216,7 @@ Example:
{
slug: 'customers',
auth: {
forgotPassword: {
verify: {
// highlight-start
generateEmailSubject: ({ req, user }) => {
return `Hey ${user.email}, reset your password!`;
@@ -211,9 +234,8 @@ As of Payload `1.0.0`, you can add additional authentication strategies to Paylo
Behind the scenes, Payload uses PassportJS to power its local authentication strategy, so most strategies listed on the PassportJS website will work seamlessly. Combined with adding custom components to the admin panel's `Login` view, you can create advanced authentication strategies directly within Payload.
<Banner type="warning">
This is an advanced feature, so only attempt this if you are an experienced
developer. Otherwise, just let Payload's built-in authentication handle user
auth for you.
This is an advanced feature, so only attempt this if you are an experienced developer. Otherwise,
just let Payload's built-in authentication handle user auth for you.
</Banner>
The `strategies` property is an array that takes objects with the following properties:
@@ -229,3 +251,42 @@ If you pass a strategy to the `strategy` property directly, the `name` property
However, if you pass a function to `strategy`, `name` is a required property.
In either case, Payload will prefix the strategy name with the collection `slug` that the strategy is passed to.
### Admin autologin
For testing and demo purposes you may want to skip forcing the admin user to login in order to access the panel.
The `admin.autologin` property is used to configure the how visitors are handled when accessing the admin panel.
The default is that all users will have to login and this should not be enabled for environments where data needs to protected.
user: { // The JWT "payload" ;) from the logged in user
@@ -108,6 +110,7 @@ query {
Accepts an `email` and `password`. On success, it will return the logged in user as well as a token that can be used to authenticate. In the GraphQL and REST APIs, this operation also automatically sets an HTTP-only cookie including the user's token. If you pass an Express `res` to the Local API operation, Payload will set a cookie there as well.
**Example REST API login**:
```ts
const res = await fetch('http://localhost:3000/api/[collection-slug]/login', {
method: 'POST',
@@ -117,10 +120,10 @@ const res = await fetch('http://localhost:3000/api/[collection-slug]/login', {
body: JSON.stringify({
email: 'dev@payloadcms.com',
password: 'this-is-not-our-password...or-is-it?',
})
}),
})
const json = await res.json();
const json = await res.json()
// JSON will be equal to the following:
/*
@@ -168,6 +171,7 @@ const result = await payload.login({
As Payload sets HTTP-only cookies, logging out cannot be done by just removing a cookie in JavaScript, as HTTP-only cookies are inaccessible by JS within the browser. So, Payload exposes a `logout` operation to delete the token in a safe way.
**Example REST API logout**:
```ts
const res = await fetch('http://localhost:3000/api/[collection-slug]/logout', {
method: 'POST',
@@ -194,6 +198,7 @@ This operation requires a non-expired token to send back a new one. If the user'
If successful, this operation will automatically renew the user's HTTP-only cookie and will send back the updated token in JSON.
**Example REST API token refresh**:
```ts
const res = await fetch('http://localhost:3000/api/[collection-slug]/refresh-token', {
method: 'POST',
@@ -202,7 +207,7 @@ const res = await fetch('http://localhost:3000/api/[collection-slug]/refresh-tok
},
})
const json = await res.json();
const json = await res.json()
// JSON will be equal to the following:
/*
@@ -233,7 +238,10 @@ mutation {
```
<Banner type="success">
The Refresh operation will automatically find the user's token in either a JWT header or the HTTP-only cookie. But, you can specify the token you're looking to refresh by providing the REST API with a `token` within the JSON body of the request, or by providing the GraphQL resolver a `token` arg.
The Refresh operation will automatically find the user's token in either a JWT header or the
HTTP-only cookie. But, you can specify the token you're looking to refresh by providing the REST
API with a `token` within the JSON body of the request, or by providing the GraphQL resolver a
`token` arg.
</Banner>
### Verify by Email
@@ -241,13 +249,14 @@ mutation {
If your collection supports email verification, the Verify operation will be exposed which accepts a verification token and sets the user's `_verified` property to `true`, thereby allowing the user to authenticate with the Payload API.
**Example REST API user verification**:
```ts
const res = await fetch(`http://localhost:3000/api/[collection-slug]/verify/${TOKEN_HERE}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
});
})
```
**Example GraphQL Mutation**:
@@ -274,6 +283,7 @@ If a user locks themselves out and you wish to deliberately unlock them, you can
To restrict who is allowed to unlock users, you can utilize the [`unlock`](/docs/access-control/overview#unlock) access control function.
**Example REST API unlock**:
```ts
const res = await fetch(`http://localhost:3000/api/[collection-slug]/unlock`, {
method: 'POST',
@@ -308,6 +318,7 @@ The link to reset the user's password contains a token which is what allows the
By default, the Forgot Password operations send users to the Payload Admin panel to reset their password, but you can customize the generated email to send users to the frontend of your app instead by [overriding the email HTML](/docs/authentication/config#forgot-password).
**Example REST API Forgot Password**:
```ts
const res = await fetch(`http://localhost:3000/api/[collection-slug]/forgot-password`, {
method: 'POST',
@@ -317,7 +328,7 @@ const res = await fetch(`http://localhost:3000/api/[collection-slug]/forgot-pass
disableEmail: false // you can disable the auto-generation of email via local API
});
disableEmail: false, // you can disable the auto-generation of email via local API
})
```
<Banner type="success">
<strong>Tip:</strong><br/>
You can stop the reset-password email from being sent via using the local API. This is helpful if you need to create user accounts programmatically, but not set their password for them. This effectively generates a reset password token which you can then use to send to a page you create, allowing a user to "complete" their account by setting their password. In the background, you'd use the token to "reset" their password.
<strong>Tip:</strong>
<br />
You can stop the reset-password email from being sent via using the local API. This is helpful if
you need to create user accounts programmatically, but not set their password for them. This
effectively generates a reset password token which you can then use to send to a page you create,
allowing a user to "complete" their account by setting their password. In the background, you'd
After a user has "forgotten" their password and a token is generated, that token can be used to send to the reset password operation along with a new password which will allow the user to reset their password securely.
**Example REST API Reset Password**:
```ts
const res = await fetch(`http://localhost:3000/api/[collection-slug]/reset-password`, {
method: 'POST',
Some files were not shown because too many files have changed in this diff
Show More
Reference in New Issue
Block a user
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.