diff --git a/docs/Admin/components.mdx b/docs/Admin/components.mdx index a358e3ed57..f1673428c0 100644 --- a/docs/Admin/components.mdx +++ b/docs/Admin/components.mdx @@ -11,40 +11,31 @@ While designing the Payload Admin panel, we determined it should be as minimal a 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. - Tip: -
- Custom components will automatically be provided with all props that the - default component would accept. + Tip:
+ Custom components will automatically be provided with all props that the default component would accept.
### 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: -| Path | Description | -| --------------------- | -------------------------------------------------------------------------------------------------- | -| **`Nav`** | Contains the sidebar and mobile Nav in its entirety. | -| **`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. | +| Path | Description | +| --------------------- | -------------| +| **`Nav`** | Contains the sidebar and mobile Nav in its entirety. | +| **`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. | +| **`graphics.Logo`** | The full logo to be used in contexts like the `Login` view. | #### Full example: `payload.config.js` - ```js -import { buildConfig } from "payload/config"; -import { - MyCustomNav, - MyCustomLogo, - MyCustomIcon, - MyCustomAccount, - MyCustomDashboard, -} from "./customComponents.js"; +import { buildConfig } from 'payload/config'; +import { MyCustomNav, MyCustomLogo, MyCustomIcon, MyCustomAccount, MyCustomDashboard } from './customComponents.js'; export default buildConfig({ - serverURL: "http://localhost:3000", + serverURL: 'http://localhost:3000', admin: { components: { Nav: MyCustomNav, @@ -55,62 +46,63 @@ export default buildConfig({ views: { Account: MyCustomAccount, Dashboard: MyCustomDashboard, - }, - }, - }, -}); + } + } + } +}) ``` -_For more examples regarding how to customize components, look at the [demo app](https://github.com/payloadcms/payload/tree/master/demo)._ +*For more examples regarding how to customize components, look at the [demo app](https://github.com/payloadcms/payload/tree/master/demo).* ### Collections You can override components on a Collection-by-Collection basis via each Collection's `admin` property. -| Path | Description | -| ---------------- | ------------------------------------------------------------------------------------------------ | -| **`views.Edit`** | Used while a document within this Collection is being edited. | -| **`views.List`** | The `List` view is used to render a paginated, filterable table of Documents in this Collection. | +| Path | Description | +| ---------------- | -------------| +| **`views.Edit`** | Used while a document within this Collection is being edited. | +| **`views.List`** | The `List` view is used to render a paginated, filterable table of Documents in this Collection. | ### Globals As with Collections, You can override components on a global-by-global basis via their `admin` property. -| Path | Description | -| ---------------- | --------------------------------------- | -| **`views.Edit`** | Used while this Global is being edited. | +| Path | Description | +| ---------------- | -------------| +| **`views.Edit`** | Used while this Global is being edited. | ### Fields All Payload fields support the ability to swap in your own React components. So, for example, instead of rendering a default Text input, you might need to render a color picker that provides the editor with a custom color picker interface to restrict the data entered to colors only. - Tip: -
- 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. + Tip:
+ 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.
**Fields support the following custom components:** -| Component | Description | -| ------------ | ------------------------------------------------------------------------------------------------------------------------ | -| **`Filter`** | Override the text input that is presented in the `List` view when a user is filtering documents by the customized field. | -| **`Cell`** | Used in the `List` view's table to represent a table-based preview of the data stored in the field. | -| **`Field`** | Swap out the field itself within all `Edit` views. | +| Component | Description | +| --------------- | -------------| +| **`Filter`** | Override the text input that is presented in the `List` view when a user is filtering documents by the customized field. | +| **`Cell`** | Used in the `List` view's table to represent a table-based preview of the data stored in the field. | +| **`Field`** | Swap out the field itself within all `Edit` views. | #### Sending and receiving values from the form 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 `useFieldType` hook as follows: ```js -import { useFieldType } from "payload/components/forms"; +import { useFieldType } from 'payload/components/forms'; const CustomTextField = ({ path }) => { const { value, setValue } = useFieldType({ path }); - return setValue(e.target.value)} value={value} />; -}; + return ( + setValue(e.target.value)} + value={value} + /> + ) +} ``` diff --git a/docs/Admin/overview.mdx b/docs/Admin/overview.mdx index 78e52ae606..04346a2478 100644 --- a/docs/Admin/overview.mdx +++ b/docs/Admin/overview.mdx @@ -11,52 +11,48 @@ Payload dynamically generates a beautiful, fully functional React admin panel to The Payload Admin panel is built with Webpack, code-split, highly performant (even with 100+ fields), and written fully in TypeScript. - 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. ![Payload's Admin panel built in React](https://payloadcms.com/images/admin.jpg) -_Screenshot of the Admin panel while editing a document from an example `AllFields` collection_ +*Screenshot of the Admin panel while editing a document from an example `AllFields` collection* ## Admin Options All options for the Admin panel are defined in your base Payload config file. -| Option | Description | -| ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| `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) | -| `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). | -| `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) | +| Option | Description | +| -------------------- | -------------| +| `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) | +| `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). | +| `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) | + ### The Admin User Collection - Important: -
- The Payload Admin panel can only be used by one Collection that supports{" "} - Authentication. + Important:
+ The Payload Admin panel can only be used by one Collection that supports Authentication.
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. `payload.config.js`: - ```js -import { buildConfig } from "payload/config"; +import { buildConfig } from 'payload/config'; const config = buildConfig({ - serverURL: "http://localhost:3000", + serverURL: 'http://localhost:3000', 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. diff --git a/docs/access-control/collections.mdx b/docs/access-control/collections.mdx index efcfa86dc9..02240d484d 100644 --- a/docs/access-control/collections.mdx +++ b/docs/access-control/collections.mdx @@ -10,24 +10,23 @@ You can define Collection-level Access Control within each Collection's `access` ## Available Controls -| Function | Allows/Denies Access | -| ----------------------- | -------------------------------------------- | -| **[`create`](#create)** | Used in the `create` operation | -| **[`read`](#read)** | Used in the `find` and `findByID` operations | -| **[`update`](#update)** | Used in the `update` operation | -| **[`delete`](#delete)** | Used in the `delete` operation | +| Function | Allows/Denies Access | +| ------------------------ | -------------------- | +| **[`create`](#create)** | Used in the `create` operation | +| **[`read`](#read)** | Used in the `find` and `findByID` operations | +| **[`update`](#update)** | Used in the `update` operation | +| **[`delete`](#delete)** | Used in the `delete` operation | #### Auth-enabled Controls If a Collection supports [`Authentication`](/docs/authentication/overview), the following Access Controls become available: -| Function | Allows/Denies Access | -| ----------------------- | -------------------------------------------------------------- | -| **[`admin`](#admin)** | Used to restrict access to the Payload Admin panel | +| Function | Allows/Denies Access | +| ----------------------- | -------------------- | +| **[`admin`](#admin)** | Used to restrict access to the Payload Admin panel | | **[`unlock`](#unlock)** | Used to restrict which users can access the `unlock` operation | **Example Collection config:** - ```js export default { slug: "posts", @@ -49,8 +48,8 @@ Returns a boolean which allows/denies access to the `create` request. **Available argument properties :** -| Option | Description | -| --------- | -------------------------------------------------------------------------- | +| Option | Description | +| --------- | ----------- | | **`req`** | The Express `request` object containing the currently authenticated `user` | ### Read @@ -59,9 +58,9 @@ Read access functions can return a boolean result or optionally return a [query **Available argument properties :** -| Option | Description | -| --------- | ------------------------------------------------------------------------------- | -| **`req`** | The Express `request` object containing the currently authenticated `user` | +| Option | Description | +| --------- | ----------- | +| **`req`** | The Express `request` object containing the currently authenticated `user` | | **`id`** | `id` of document requested, if within `findByID`. Otherwise, `id` is undefined. | ### Update @@ -70,10 +69,10 @@ Update access functions can return a boolean result or optionally return a [quer **Available argument properties :** -| Option | Description | -| --------- | -------------------------------------------------------------------------- | +| Option | Description | +| --------- | ----------- | | **`req`** | The Express `request` object containing the currently authenticated `user` | -| **`id`** | `id` of document requested to update | +| **`id`** | `id` of document requested to update | ### Delete @@ -81,10 +80,10 @@ Similarly to the Update function, returns a boolean or a [query constraint](/doc **Available argument properties :** -| Option | Description | -| --------- | --------------------------------------------------------------------------------------------------- | +| Option | Description | +| --------- | ----------- | | **`req`** | The Express `request` object with additional `user` property, which is the currently logged in user | -| **`id`** | `id` of document requested to delete | +| **`id`** | `id` of document requested to delete | ### Admin @@ -92,8 +91,8 @@ If the Collection is [used to access the Payload Admin panel](/docs/admin/overvi **Available argument properties :** -| Option | Description | -| --------- | -------------------------------------------------------------------------- | +| Option | Description | +| --------- | ----------- | | **`req`** | The Express `request` object containing the currently authenticated `user` | ### Unlock @@ -102,6 +101,6 @@ Determines which users can [unlock](/docs/authentication/operations#unlock) othe **Available argument properties :** -| Option | Description | -| --------- | -------------------------------------------------------------------------- | +| Option | Description | +| --------- | ----------- | | **`req`** | The Express `request` object containing the currently authenticated `user` | diff --git a/docs/access-control/fields.mdx b/docs/access-control/fields.mdx index 7eebd31b85..2e2f1feb4b 100644 --- a/docs/access-control/fields.mdx +++ b/docs/access-control/fields.mdx @@ -10,14 +10,13 @@ Field Access Control is specified with functions inside a field's config. All fi ## Available Controls -| Function | Purpose | -| ----------------------- | -------------------------------------------------------------------------------- | -| **[`create`](#create)** | Allows or denies the ability to set a field's value when creating a new document | -| **[`read`](#read)** | Allows or denies the ability to read a field's value | -| **[`update`](#update)** | Allows or denies the ability to update a field's value | +| Function | Purpose | +| ------------------------ | ------- | +| **[`create`](#create)** | Allows or denies the ability to set a field's value when creating a new document | +| **[`read`](#read)** | Allows or denies the ability to read a field's value | +| **[`update`](#update)** | Allows or denies the ability to update a field's value | **Example Collection config:** - ```js export default { slug: 'posts', @@ -44,8 +43,8 @@ Returns a boolean which allows or denies the ability to set a field's value when **Available argument properties:** -| Option | Description | -| --------- | -------------------------------------------------------------------------- | +| Option | Description | +| --------- | ----------- | | **`req`** | The Express `request` object containing the currently authenticated `user` | ### Read @@ -54,10 +53,10 @@ Returns a boolean which allows or denies the ability to read a field's value. If **Available argument properties:** -| Option | Description | -| --------- | -------------------------------------------------------------------------- | +| Option | Description | +| --------- | ----------- | | **`req`** | The Express `request` object containing the currently authenticated `user` | -| **`id`** | `id` of the document being read | +| **`id`** | `id` of the document being read | ### Update @@ -65,7 +64,7 @@ Returns a boolean which allows or denies the ability to update a field's value. **Available argument properties:** -| Option | Description | -| --------- | -------------------------------------------------------------------------- | +| Option | Description | +| --------- | ----------- | | **`req`** | The Express `request` object containing the currently authenticated `user` | -| **`id`** | `id` of the document being updated | +| **`id`** | `id` of the document being updated | diff --git a/docs/access-control/globals.mdx b/docs/access-control/globals.mdx index 8c10217cd3..ede92e788f 100644 --- a/docs/access-control/globals.mdx +++ b/docs/access-control/globals.mdx @@ -8,17 +8,16 @@ keywords: globals, access control, permissions, documentation, Content Managemen You can define Global-level Access Control within each Global's `access` property. All Access Control functions accept one `args` argument. -\*\*Available argument properties: +**Available argument properties: ## Available Controls -| Function | Allows/Denies Access | -| ----------------------- | -------------------------------------- | -| **[`read`](#read)** | Used in the `findOne` Global operation | -| **[`update`](#update)** | Used in the `update` Global operation | +| Function | Allows/Denies Access | +| ------------------------ | -------------------- | +| **[`read`](#read)** | Used in the `findOne` Global operation | +| **[`update`](#update)** | Used in the `update` Global operation | **Example Global config:** - ```js export default { slug: "header", @@ -37,8 +36,8 @@ Returns a boolean result to allow or deny a user's ability to read the Global. **Available argument properties:** -| Option | Description | -| --------- | -------------------------------------------------------------------------- | +| Option | Description | +| --------- | ----------- | | **`req`** | The Express `request` object containing the currently authenticated `user` | ### Update @@ -47,6 +46,6 @@ Returns a boolean result to allow or deny a user's ability to update the Global. **Available argument properties:** -| Option | Description | -| --------- | -------------------------------------------------------------------------- | +| Option | Description | +| --------- | ----------- | | **`req`** | The Express `request` object containing the currently authenticated `user` | diff --git a/docs/access-control/overview.mdx b/docs/access-control/overview.mdx index 8bf492cbd8..70c341b71c 100644 --- a/docs/access-control/overview.mdx +++ b/docs/access-control/overview.mdx @@ -28,15 +28,12 @@ const defaultPayloadAccess = ({ req: { user } }) => { // Return `true` if a user is found // and `false` if it is undefined or null return Boolean(user); -}; +} ``` - Note: -
- 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 overrideAccess to true. + Note:
+ 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 overrideAccess to true.
### Access Control Types diff --git a/docs/authentication/config.mdx b/docs/authentication/config.mdx index af93c6a2f0..10f2299709 100644 --- a/docs/authentication/config.mdx +++ b/docs/authentication/config.mdx @@ -12,16 +12,16 @@ To enable Authentication on a collection, define an `auth` property and set it t ## Options -| Option | Description | -| ---------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| **`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 that a user should be locked out if they fail authentication more times than `maxLoginAttempts` allows for. | +| Option | Description | +| ---------------------- | -------------| +| **`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 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) | -| **`verify`** | Set to `true` or pass an object with verification options to require users to verify by email before they are allowed to log into your app. [More](/docs/authentication/config#email-verification) | +| **`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) | +| **`verify`** | Set to `true` or pass an object with verification options to require users to verify by email before they are allowed to log into your app. [More](/docs/authentication/config#email-verification) | ### API keys @@ -37,8 +37,7 @@ Technically, both of these options will work for third-party integrations but th 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. - 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. ##### Authenticating via API Key @@ -46,9 +45,8 @@ To enable API keys on a collection, set the `useAPIKey` auth option to `true`. F To utilize your API key while interacting with the REST or GraphQL API, add the `Authorization` header. **For example, using Fetch:** - ```js -const response = await fetch("http://localhost:3000/api/pages", { +const response = await fetch('http://localhost:3000/api/pages', { headers: { Authorization: `${collection.labels.singular} API-Key ${YOUR_API_KEY}`, }, @@ -64,13 +62,8 @@ You can customize how the Forgot Password workflow operates with the following o Function that accepts one argument, containing `{ req, token, user }`, that allows for overriding the HTML within emails that are sent to users attempting to reset their password. The function should return a string that supports HTML, which can be a full HTML email. - Tip: -
- 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. + Tip:
+ 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.
Example: @@ -106,13 +99,8 @@ Example: ``` - Important: -
- If you specify a different URL to send your users to for resetting their - password, 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 reset-password operation - yourself on your frontend, using the token that was provided for you. Above, - it was passed via query parameter. + Important:
+ If you specify a different URL to send your users to for resetting their password, 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 reset-password operation yourself on your frontend, using the token that was provided for you. Above, it was passed via query parameter.
**`generateEmailSubject`** @@ -165,13 +153,8 @@ Example: ``` - Important: -
- 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. + Important:
+ 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.
**`generateEmailSubject`** diff --git a/docs/authentication/operations.mdx b/docs/authentication/operations.mdx index 548f173e07..e2b11beda9 100644 --- a/docs/authentication/operations.mdx +++ b/docs/authentication/operations.mdx @@ -17,7 +17,6 @@ The Access operation returns what a logged in user can and can't do with the col `GET http://localhost:3000/api/access` Example response: - ```js { canAccessAdmin: true, @@ -77,7 +76,6 @@ Returns either a logged in user with token or null when there is no logged in us `GET http://localhost:3000/api/[collection-slug]/me` Example response: - ```js { user: { // The JWT "payload" ;) from the logged in user @@ -109,18 +107,17 @@ 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**: - ```js -const res = await fetch("http://localhost:3000/api/[collection-slug]/login", { - method: "POST", +const res = await fetch('http://localhost:3000/api/[collection-slug]/login', { + method: 'POST', headers: { - "Content-Type": "application/json", + 'Content-Type': 'application/json', }, body: JSON.stringify({ - email: "dev@payloadcms.com", - password: "this-is-not-our-password...or-is-it?", - }), -}); + email: 'dev@payloadcms.com', + password: 'this-is-not-our-password...or-is-it?', + }) +}) const json = await res.json(); @@ -157,12 +154,12 @@ mutation { ```js const result = await payload.login({ - collection: "[collection-slug]", + collection: '[collection-slug]', data: { - email: "dev@payloadcms.com", - password: "get-out", + email: 'dev@payloadcms.com', + password: 'get-out', }, -}); +}) ``` ### Logout @@ -170,14 +167,13 @@ 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**: - ```js -const res = await fetch("http://localhost:3000/api/[collection-slug]/logout", { - method: "POST", +const res = await fetch('http://localhost:3000/api/[collection-slug]/logout', { + method: 'POST', headers: { - "Content-Type": "application/json", + 'Content-Type': 'application/json', }, -}); +}) ``` **Example GraphQL Mutation**: @@ -197,14 +193,13 @@ 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**: - ```js -const res = await fetch("http://localhost:3000/api/[collection-slug]/refresh", { - method: "POST", +const res = await fetch('http://localhost:3000/api/[collection-slug]/refresh', { + method: 'POST', headers: { - "Content-Type": "application/json", + 'Content-Type': 'application/json', }, -}); +}) const json = await res.json(); @@ -237,10 +232,7 @@ mutation { ``` - 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. ### Verify by Email @@ -248,17 +240,13 @@ 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**: - ```js -const res = await fetch( - `http://localhost:3000/api/[collection-slug]/verify/${TOKEN_HERE}`, - { - method: "POST", - headers: { - "Content-Type": "application/json", - }, - } -); +const res = await fetch(`http://localhost:3000/api/[collection-slug]/verify/${TOKEN_HERE}`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + }, +}) ``` **Example GraphQL Mutation**: @@ -273,9 +261,9 @@ mutation { ```js const result = await payload.verifyEmail({ - collection: "[collection-slug]", - token: "TOKEN_HERE", -}); + collection: '[collection-slug]', + token: 'TOKEN_HERE', +}) ``` ### Unlock @@ -285,14 +273,13 @@ 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**: - ```js const res = await fetch(`http://localhost:3000/api/[collection-slug]/unlock`, { - method: "POST", + method: 'POST', headers: { - "Content-Type": "application/json", + 'Content-Type': 'application/json', }, -}); +}) ``` **Example GraphQL Mutation**: @@ -307,8 +294,8 @@ mutation { ```js const result = await payload.unlock({ - collection: "[collection-slug]", -}); + collection: '[collection-slug]', +}) ``` ### Forgot Password @@ -320,20 +307,16 @@ 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**: - ```js -const res = await fetch( - `http://localhost:3000/api/[collection-slug]/forgot-password`, - { - method: "POST", - headers: { - "Content-Type": "application/json", - }, - body: JSON.stringify({ - email: "dev@payloadcms.com", - }), - } -); +const res = await fetch(`http://localhost:3000/api/[collection-slug]/forgot-password`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ + email: 'dev@payloadcms.com', + }), +}) ``` **Example GraphQL Mutation**: @@ -348,23 +331,17 @@ mutation { ```js const token = await payload.forgotPassword({ - collection: "[collection-slug]", + collection: '[collection-slug]', data: { - email: "dev@payloadcms.com", + email: 'dev@payloadcms.com', }, - 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 +}) ``` - Tip: -
- 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. + Tip:
+ 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.
### Reset Password @@ -372,7 +349,6 @@ const token = await payload.forgotPassword({ 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**: - ```js const res = await fetch(`http://localhost:3000/api/[collection-slug]/reset-password`, { method: 'POST', diff --git a/docs/authentication/overview.mdx b/docs/authentication/overview.mdx index 3d8a842891..80fa69a6eb 100644 --- a/docs/authentication/overview.mdx +++ b/docs/authentication/overview.mdx @@ -7,14 +7,13 @@ keywords: authentication, config, configuration, overview, documentation, Conten --- - Payload provides for highly secure and customizable user Authentication out of - the box, which allows for users to identify themselves to Payload. + Payload provides for highly secure and customizable user Authentication out of the box, which allows for users to identify themselves to Payload. Authentication is used within the Payload Admin panel itself as well as throughout your app(s) themselves however you determine necessary. ![Authentication admin panel functionality](https://payloadcms.com/images/auth-admin.jpg) -_Admin panel screenshot depicting an Admins Collection with Auth enabled_ +*Admin panel screenshot depicting an Admins Collection with Auth enabled* **Here are some common use cases of Authentication outside of Payload's dashboard itself:** @@ -78,11 +77,8 @@ Once enabled, each document that is created within the Collection can be thought Successfully logging in returns a `JWT` (JSON web token) which is how a user will identify themselves to Payload. By providing this JWT via either an HTTP-only cookie or an `Authorization` header, Payload will automatically identify the user and add its user JWT data to the Express `req`, which is available throughout Payload including within access control, hooks, and more. - Tip: -
- You can access the logged in user from access control functions and hooks via - the Express req. The logged in user is automatically added as - the user property. + Tip:
+ You can access the logged in user from access control functions and hooks via the Express req. The logged in user is automatically added as the user property.
### HTTP-only cookies @@ -100,8 +96,8 @@ However, if you use `fetch` or similar APIs to retrieve Payload resources from i Fetch example, including credentials: ```js -const response = await fetch("http://localhost:3000/api/pages", { - credentials: "include", +const response = await fetch('http://localhost:3000/api/pages', { + credentials: 'include', }); const pages = await response.json(); @@ -110,12 +106,8 @@ const pages = await response.json(); For more about how to automatically include cookies in requests from your app to your Payload API, [click here](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#Sending_a_request_with_credentials_included). - Tip: -
- To make sure you have a Payload cookie set properly in your browser after - logging in, you can use Chrome's Developer Tools - Application - Cookies - - [your-domain-here]. The Chrome Developer tools will still show HTTP-only - cookies, even when JavaScript running on the page can't. + Tip:
+ To make sure you have a Payload cookie set properly in your browser after logging in, you can use Chrome's Developer Tools - Application - Cookies - [your-domain-here]. The Chrome Developer tools will still show HTTP-only cookies, even when JavaScript running on the page can't.
### CSRF Protection @@ -127,29 +119,24 @@ For example, let's say you have a very popular app running at coolsite.com. This So, if a user of coolsite.com is logged in and just browsing around on the internet, they might stumble onto a page with bad intentions. That bad page might automatically make requests to all sorts of sites to see if they can find one that they can log into - and coolsite.com might be on their list. If your user was logged in while they visited that evil site, the attacker could do whatever they wanted as if they were your coolsite.com user by just sending requests to the coolsite API (which would automatically include the auth cookie). They could send themselves a bunch of money from your user's account, change the user's password, etc. This is what a CSRF attack is. - - To protect against CSRF attacks, Payload only accepts cookie-based - authentication from domains that you explicitly whitelist. - + To protect against CSRF attacks, Payload only accepts cookie-based authentication from domains that you explicitly whitelist. To define domains that should allow users to identify themselves via the Payload HTTP-only cookie, use the `csrf` option on the base Payload config to whitelist domains that you trust. `payload.config.js`: - ```js -import { buildConfig } from "payload/config"; +import { buildConfig } from 'payload/config'; const config = buildConfig({ - serverURL: "http://localhost:3000", + serverURL: 'http://localhost:3000', collections: [ // collections here ], // highlight-start - csrf: [ - // whitelist of domains to allow cookie auth from - "https://your-frontend-app.com", - "https://your-other-frontend-app.com", + csrf: [ // whitelist of domains to allow cookie auth from + 'https://your-frontend-app.com', + 'https://your-other-frontend-app.com', ], // highlight-end }); @@ -162,13 +149,12 @@ export default config; In addition to authenticating via an HTTP-only cookie, you can also identify users via the `Authorization` header on an HTTP request. Example: - ```js -const request = await fetch("http://localhost:3000", { +const request = await fetch('http://localhost:3000', { headers: { - Authorization: `JWT ${token}`, - }, -}); + Authorization: `JWT ${token}` + } +}) ``` You can retrieve a user's token via the response to `login`, `refresh`, and `me` auth operations. diff --git a/docs/authentication/using-middleware.mdx b/docs/authentication/using-middleware.mdx index 64cb267e00..05da465800 100644 --- a/docs/authentication/using-middleware.mdx +++ b/docs/authentication/using-middleware.mdx @@ -6,26 +6,24 @@ desc: Make full use of Payload's built-in authentication with your own custom Ex keywords: authentication, middleware, config, configuration, documentation, Content Management System, cms, headless, javascript, node, react, express --- -Because Payload uses your existing Express server, you are free to add whatever logic you need to your app through endpoints of your own. However, Payload does not add its middleware to your Express app itself—instead, it scopes all of its middleware to Payload-specific routers. +Because Payload uses your existing Express server, you are free to add whatever logic you need to your app through endpoints of your own. However, Payload does not add its middleware to your Express app itself—instead, ist scopes all of its middleware to Payload-specific routers. This approach has a ton of benefits - it's great for isolation of concerns and limiting scope, but it also means that your additional routes won't have access to Payload's user authentication. - You can make full use of Payload's built-in authentication within your own - custom Express endpoints by adding Payload's authentication middleware. + You can make full use of Payload's built-in authentication within your own custom Express endpoints by adding Payload's authentication middleware. Example in `server.js`: - ```js -import express from "express"; -import payload from "payload"; +import express from 'express'; +import payload from 'payload'; const app = express(); payload.init({ - secret: "PAYLOAD_SECRET_KEY", - mongoURL: "mongodb://localhost/payload", + secret: 'PAYLOAD_SECRET_KEY', + mongoURL: 'mongodb://localhost/payload', express: app, }); @@ -33,17 +31,18 @@ const router = express.Router(); router.use(payload.authenticate); // highlight-line -router.get("/", (req, res) => { +router.get('/', (req, res) => { if (req.user) { return res.send(`Authenticated successfully as ${req.user.email}.`); } - return res.send("Not authenticated"); + return res.send('Not authenticated'); }); -app.use("/some-route-here", router); +app.use('/some-route-here', router); app.listen(3000, async () => { payload.logger.info(`listening on ${3000}...`); }); + ``` diff --git a/docs/configuration/collections.mdx b/docs/configuration/collections.mdx index bd4fa728a5..a737ff4fea 100644 --- a/docs/configuration/collections.mdx +++ b/docs/configuration/collections.mdx @@ -12,43 +12,43 @@ It's often best practice to write your Collections in separate files and then im ## Options -| Option | Description | -| ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| **`slug`** \* | Unique, URL-friendly string that will act as an identifier for this Collection. | -| **`fields`** \* | Array of field types that will determine the structure and functionality of the data stored within this Collection. [Click here](/docs/fields/overview) for a full list of field types as well as how to configure them. | -| **`labels`** | Singular and plural labels for use in identifying this Collection throughout Payload. | -| **`admin`** | Admin-specific configuration. See below for [more detail](/docs/collections#admin). | -| **`hooks`** | Entry points to "tie in" to Collection actions at specific points. [More](/docs/hooks/overview#collection-hooks) | -| **`access`** | Provide access control functions to define exactly who should be able to do what with Documents in this Collection. [More](/docs/access-control/overview/#collections) | -| **`auth`** | Specify options if you would like this Collection to feature authentication. For more, consult the [Authentication](/docs/authentication/config) documentation. | -| **`upload`** | Specify options if you would like this Collection to support file uploads. For more, consult the [Uploads](/docs/uploads/overview) documentation. | -| **`timestamps`** | Set to false to disable documents' automatically generated `createdAt` and `updatedAt` timestamps. | +| Option | Description | +| ---------------- | -------------| +| **`slug`** * | Unique, URL-friendly string that will act as an identifier for this Collection. | +| **`fields`** * | Array of field types that will determine the structure and functionality of the data stored within this Collection. [Click here](/docs/fields/overview) for a full list of field types as well as how to configure them. | +| **`labels`** | Singular and plural labels for use in identifying this Collection throughout Payload. | +| **`admin`** | Admin-specific configuration. See below for [more detail](/docs/collections#admin). | +| **`hooks`** | Entry points to "tie in" to Collection actions at specific points. [More](/docs/hooks/overview#collection-hooks) | +| **`access`** | Provide access control functions to define exactly who should be able to do what with Documents in this Collection. [More](/docs/access-control/overview/#collections) | +| **`auth`** | Specify options if you would like this Collection to feature authentication. For more, consult the [Authentication](/docs/authentication/config) documentation. | +| **`upload`** | Specify options if you would like this Collection to support file uploads. For more, consult the [Uploads](/docs/uploads/overview) documentation. | +| **`timestamps`** | Set to false to disable documents' automatically generated `createdAt` and `updatedAt` timestamps. | -_\* An asterisk denotes that a property is required._ +*\* An asterisk denotes that a property is required.* #### Simple collection example ```js const Order = { - slug: "orders", - labels: { - singular: "Order", - plural: "Orders", - }, - fields: [ - { - name: "total", - type: "number", - required: true, - }, - { - name: "placedBy", - type: "relationship", - relationTo: "customers", - required: true, - }, - ], -}; + slug: 'orders', + labels: { + singular: 'Order', + plural: 'Orders', + }, + fields: [ + { + name: 'total', + type: 'number', + required: true, + }, + { + name: 'placedBy', + type: 'relationship', + relationTo: 'customers', + required: true, + } + ] +} ``` #### More collection config examples @@ -59,14 +59,14 @@ You can find an assortment of [example collection configs](https://github.com/pa You can customize the way that the Admin panel behaves on a collection-by-collection basis by defining the `admin` property on a collection's config. -| Option | Description | -| ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `useAsTitle` | Specify a top-level field to use for a document title throughout the Admin panel. If no field is defined, the ID of the document is used as the title. | -| `defaultColumns` | Array of field names that correspond to which columns to show by default in this collection's List view. | -| `disableDuplicate ` | Disables the "Duplicate" button while editing documents within this collection. | +| Option | Description | +| ---------------------------- | -------------| +| `useAsTitle` | Specify a top-level field to use for a document title throughout the Admin panel. If no field is defined, the ID of the document is used as the title. | +| `defaultColumns` | Array of field names that correspond to which columns to show by default in this collection's List view. | +| `disableDuplicate ` | Disables the "Duplicate" button while editing documents within this collection. | | `enableRichTextRelationship` | The [Rich Text](/docs/fields/rich-text) field features a `Relationship` element which allows for users to automatically reference related documents within their rich text. Set this field to `true` to enable the collection to be selected within it. | -| `preview` | Function to generate preview URLS within the Admin panel that can point to your app. [More](/docs/collections#preview). | -| `components` | Swap in your own React components to be used within this collection. [More](/docs/admin/components#collections) | +| `preview` | Function to generate preview URLS within the Admin panel that can point to your app. [More](/docs/collections#preview). | +| `components` | Swap in your own React components to be used within this collection. [More](/docs/admin/components#collections) | ### Preview diff --git a/docs/configuration/globals.mdx b/docs/configuration/globals.mdx index a8f40b1126..c93e530c2d 100644 --- a/docs/configuration/globals.mdx +++ b/docs/configuration/globals.mdx @@ -6,47 +6,47 @@ desc: Set up your Global config for your needs by defining fields, adding slugs keywords: globals, config, configuration, documentation, Content Management System, cms, headless, javascript, node, react, express --- -Global configs are in many ways similar to [Collections](/docs/configuration/collections). The big difference is that Collections will potentially contain _many_ documents, while a Global is a "one-off". Globals are perfect for things like header nav, site-wide banner alerts, app-wide localized strings, and other "global" data that your site or app might rely on. +Global configs are in many ways similar to [Collections](/docs/configuration/collections). The big difference is that Collections will potentially contain *many* documents, while a Global is a "one-off". Globals are perfect for things like header nav, site-wide banner alerts, app-wide localized strings, and other "global" data that your site or app might rely on. As with Collection configs, it's often best practice to write your Globals in separate files and then import them into the main Payload config. ## Options -| Option | Description | -| --------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| **`slug`** \* | Unique, URL-friendly string that will act as an identifier for this Global. | -| **`fields`** \* | Array of field types that will determine the structure and functionality of the data stored within this Global. [Click here](/docs/fields/overview) for a full list of field types as well as how to configure them. | -| **`label`** | Singular label for use in identifying this Global throughout Payload. | -| **`admin`** | Admin-specific configuration. See below for [more detail](/docs/configuration/globals#admin-options). | -| **`hooks`** | Entry points to "tie in" to collection actions at specific points. [More](/docs/hooks/overview#global-hooks) | -| **`access`** | Provide access control functions to define exactly who should be able to do what with this Global. [More](/docs/access-control/overview/#globals) | +| Option | Description | +| ---------------- | -------------| +| **`slug`** * | Unique, URL-friendly string that will act as an identifier for this Global. | +| **`fields`** * | Array of field types that will determine the structure and functionality of the data stored within this Global. [Click here](/docs/fields/overview) for a full list of field types as well as how to configure them. | +| **`label`** | Singular label for use in identifying this Global throughout Payload. | +| **`admin`** | Admin-specific configuration. See below for [more detail](/docs/configuration/globals#admin-options). | +| **`hooks`** | Entry points to "tie in" to collection actions at specific points. [More](/docs/hooks/overview#global-hooks) | +| **`access`** | Provide access control functions to define exactly who should be able to do what with this Global. [More](/docs/access-control/overview/#globals) | -_\* An asterisk denotes that a property is required._ +*\* An asterisk denotes that a property is required.* #### Simple Global example ```js const Nav = { - slug: "nav", - label: "Nav", - fields: [ - { - name: "items", - type: "array", - required: true, - maxRows: 8, - fields: [ - { - name: "page", - label: "Page", - type: "relationship", - relationTo: "pages", // "pages" is the slug of an existing collection - required: true, - }, - ], - }, - ], -}; + slug: 'nav', + label: 'Nav', + fields: [ + { + name: 'items', + type: 'array', + required: true, + maxRows: 8, + fields: [ + { + name: 'page', + label: 'Page', + type: 'relationship', + relationTo: 'pages', // "pages" is the slug of an existing collection + required: true, + } + ] + }, + ] +} ``` #### More Global config examples @@ -57,9 +57,9 @@ You can find an assortment of [example Global configs](https://github.com/payloa You can customize the way that the Admin panel behaves on a Global-by-Global basis by defining the `admin` property on a Global's config. -| Option | Description | -| ------------ | ------------------------------------------------------------------------------------------------------- | -| `components` | Swap in your own React components to be used within this Global. [More](/docs/admin/components#globals) | +| Option | Description | +| ---------------------------- | -------------| +| `components` | Swap in your own React components to be used within this Global. [More](/docs/admin/components#globals) | ### Access control diff --git a/docs/configuration/localization.mdx b/docs/configuration/localization.mdx index 0a9f3492cf..607276068e 100644 --- a/docs/configuration/localization.mdx +++ b/docs/configuration/localization.mdx @@ -68,13 +68,8 @@ With the above configuration, the `title` field will now be saved in the databas All field types with a `name` property support the `localized` property—even the more complex field types like `array`s and `block`s. - Note: -
- Enabling localization for field types that support nested fields will - automatically create localized "sets" of all fields contained within the - field. For example, if you have a page layout using a blocks field type, you - have the choice of either localizing the full layout, by enabling localization - on the top-level blocks field, or only certain fields within the layout. + Note:
+ Enabling localization for field types that support nested fields will automatically create localized "sets" of all fields contained within the field. For example, if you have a page layout using a blocks field type, you have the choice of either localizing the full layout, by enabling localization on the top-level blocks field, or only certain fields within the layout.
### Retrieving localized docs @@ -111,19 +106,16 @@ The `fallbackLocale` arg will accept valid locales as well as `none` to disable ```graphql query { - Posts(locale: de, fallbackLocale: none) { - docs { - title - } - } + Posts(locale: de, fallbackLocale: none) { + docs { + title + } + } } ``` - In GraphQL, specifying the locale at the top level of a query will - automatically apply it throughout all nested relationship fields. You can - override this behavior by re-specifying locale arguments in nested related - document queries. + In GraphQL, specifying the locale at the top level of a query will automatically apply it throughout all nested relationship fields. You can override this behavior by re-specifying locale arguments in nested related document queries. ##### Local API @@ -134,8 +126,8 @@ You can specify `locale` as well as `fallbackLocale` within the Local API as wel ```js const posts = await payload.find({ - collection: "posts", - locale: "es", - fallbackLocale: false, -}); + collection: 'posts', + locale: 'es', + fallbackLocale: false, +}) ``` diff --git a/docs/configuration/overview.mdx b/docs/configuration/overview.mdx index c799affe75..b09886409c 100644 --- a/docs/configuration/overview.mdx +++ b/docs/configuration/overview.mdx @@ -6,20 +6,12 @@ desc: The Payload config is central to everything that Payload does, from adding keywords: overview, config, configuration, documentation, Content Management System, cms, headless, javascript, node, react, express --- -Payload is a _config-based_, code-first CMS and application framework. The Payload config is central to everything that Payload does. It scaffolds the data that Payload stores as well as maintains custom React components, hook logic, custom validations, and much more. The config itself and all of its dependencies are run through Babel, so you can take full advantage of newer JavaScript features and even directly import React components containing JSX. +Payload is a *config-based*, code-first CMS and application framework. The Payload config is central to everything that Payload does. It scaffolds the data that Payload stores as well as maintains custom React components, hook logic, custom validations, and much more. The config itself and all of its dependencies are run through Babel, so you can take full advantage of newer JavaScript features and even directly import React components containing JSX. - - Also, because the Payload source code is fully written in TypeScript, its - configs are strongly typed—meaning that even if you aren't using TypeScript to - build your project, your IDE (such as VSCode) may still provide helpful - information like type-ahead suggestions while you write your config. - +Also, because the Payload source code is fully written in TypeScript, its configs are strongly typed—meaning that even if you aren't using TypeScript to build your project, your IDE (such as VSCode) may still provide helpful information like type-ahead suggestions while you write your config. - Important: -
- This file is included in the Payload admin bundle, so make sure you do not - embed any sensitive information. + Important:
This file is included in the Payload admin bundle, so make sure you do not embed any sensitive information.
## Options @@ -37,7 +29,7 @@ Payload is a _config-based_, code-first CMS and application framework. The Paylo | `csrf` | A whitelist array of URLs to allow Payload cookies to be accepted from as a form of CSRF protection. [More](/docs/authentication/overview#csrf-protection) | | `defaultDepth` | If a user does not specify `depth` while requesting a resource, this depth will be used. [More](/docs/getting-started/concepts#depth) | | `maxDepth` | The maximum allowed depth to be permitted application-wide. This setting helps prevent against malicious queries. Defaults to `10`. | -| `upload` | Base Payload upload configuration. [More](/docs/upload/overview#payload-wide-upload-options). | +| `upload` | Base Payload upload configuration. [More](/docs/admin/upload#global). | | `routes` | Control the routing structure that Payload binds itself to. Specify `admin`, `api`, `graphQL`, and `graphQLPlayground`. | | `email` | Base email settings to allow Payload to generate email such as Forgot Password requests and other requirements. [More](/docs/email/overview#config) | | `express` | Express-specific middleware options such as compression and JSON parsing. [More](/docs/configuration/express). | @@ -48,53 +40,54 @@ Payload is a _config-based_, code-first CMS and application framework. The Paylo #### Simple example ```js -import { buildConfig } from "payload/config"; +import { buildConfig } from 'payload/config'; const config = buildConfig({ - serverURL: "http://localhost:3000", - collections: [ - { - slug: "pages", - fields: [ - { - name: "title", - label: "Title", - type: "text", - required: true, - }, - { - name: "content", - label: "Content", - type: "richText", - required: true, - }, - ], - }, - ], - globals: [ - { - slug: "header", - label: "Header", - fields: [ - { - name: "nav", - label: "Nav", - type: "array", - fields: [ - { - name: "page", - label: "Page", - type: "relationship", - relationTo: "pages", - }, - ], - }, - ], - }, - ], + serverURL: 'http://localhost:3000', + collections: [ + { + slug: 'pages', + fields: [ + { + name: 'title', + label: 'Title', + type: 'text', + required: true, + }, + { + name: 'content', + label: 'Content', + type: 'richText', + required: true, + } + ] + } + ], + globals: [ + { + slug: 'header', + label: 'Header', + fields: [ + { + name: 'nav', + label: 'Nav', + type: 'array', + fields: [ + { + name: 'page', + label: 'Page', + type: 'relationship', + relationTo: 'pages', + }, + ] + } + ] + } + ] }); export default config; + ``` #### Full example config @@ -106,7 +99,6 @@ You can see a full [example config](https://github.com/payloadcms/payload/blob/m We suggest using the `dotenv` package to handle environment variables alongside of Payload. All that's necessary to do is to require the package as high up in your application as possible (for example, at the top of your `server.js` file), and ensure that it can find an `.env` file that you create. **Add this line to the top of your server:** - ``` require('dotenv').config() // ... @@ -124,13 +116,8 @@ project-name ``` - Important: -
- If you use an environment variable to configure any properties that are - required for the Admin panel to function (ex. serverURL or any routes), you - need to make sure that your Admin panel code can access it.{" "} - Click here for more - info. + Important:
+ If you use an environment variable to configure any properties that are required for the Admin panel to function (ex. serverURL or any routes), you need to make sure that your Admin panel code can access it. Click here for more info.
### Customizing & overriding the config location diff --git a/docs/email/overview.mdx b/docs/email/overview.mdx index 393eb31335..afcb2cfc7b 100644 --- a/docs/email/overview.mdx +++ b/docs/email/overview.mdx @@ -25,21 +25,20 @@ in the `email` property object of your payload init call. Payload will make use The following options are configurable in the `email` property object as part of the options object when calling payload.init(). -| Option | Description | -| ---------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| **`transport`** | The NodeMailer transport object for when you want to do it yourself, not needed when transportOptions is set | -| **`transportOptions`** | An object that configures the transporter that Payload will create. For all the available options see the [NodeMailer documentation](https://nodemailer.com/smtp/) or see the examples below | -| **`fromName`** \* | The name part of the From field that will be seen on the delivered email | -| **`fromAddress`** \* | The email address part of the From field that will be used when delivering email | +| Option | Description | +| ---------------------------- | -------------| +| **`transport`** | The NodeMailer transport object for when you want to do it yourself, not needed when transportOptions is set | +| **`transportOptions`** | An object that configures the transporter that Payload will create. For all the available options see the [NodeMailer documentation](https://nodemailer.com/smtp/) or see the examples below | +| **`fromName`** * | The name part of the From field that will be seen on the delivered email | +| **`fromAddress`** * | The email address part of the From field that will be used when delivering email | -_\* An asterisk denotes that a property is required._ +*\* An asterisk denotes that a property is required.* ### Use SMTP Simple Mail Transfer Protocol, also known as SMTP can be passed in using the `transportOptions` object on the `email` options. **Example email part using SMTP:** - ```js payload.init({ email: { @@ -63,12 +62,7 @@ payload.init({ ``` - It is best practice to avoid saving credentials or API keys directly in your - code, use{" "} - - environment variables - - . + It is best practice to avoid saving credentials or API keys directly in your code, use environment variables. ### Use an email service @@ -76,28 +70,25 @@ payload.init({ Many third party mail providers are available and offer benefits beyond basic SMTP. As an example your payload init could look this if you wanted to use SendGrid.com though the same approach would work for any other [NodeMailer transports](https://nodemailer.com/transports/) shown here or provided by another third party. ```js -const nodemailerSendgrid = require("nodemailer-sendgrid"); -const payload = require("payload"); +const nodemailerSendgrid = require('nodemailer-sendgrid'); +const payload = require('payload'); const sendGridAPIKey = process.env.SENDGRID_API_KEY; payload.init({ - ...(sendGridAPIKey - ? { - email: { - transportOptions: nodemailerSendgrid({ - apiKey: sendGridAPIKey, - }), - fromName: "Admin", - fromAddress: "admin@example.com", - }, - } - : {}), + ...sendGridAPIKey ? { + email: { + transportOptions: nodemailerSendgrid({ + apiKey: sendGridAPIKey, + }), + fromName: 'Admin', + fromAddress: 'admin@example.com', + }, + } : {}, }); ``` ### Use a custom NodeMailer transport - To take full control of the mail transport you may wish to use `nodemailer.createTransport()` on your server and provide it to Payload init. ```js @@ -123,15 +114,12 @@ payload.init({ ``` ### Sending Mail - With a working transport you can call it anywhere you have access to payload by calling `payload.sendEmail(message)`. The `message` will contain the `to`, `subject` and `email` or `text` for the email being sent. To see all available message configuration options see [NodeMailer](https://nodemailer.com/message). ### Mock transport - By default, Payload uses a mock implementation that only sends mail to the [ethereal](https://ethereal.email) capture service that will never reach a user's inbox. While in development you may wish to make use of the captured messages which is why the payload output during server output helpfully logs this out on the server console. **Console output when starting payload with a mock email instance** - ``` [06:37:21] INFO (payload): Starting Payload... [06:37:22] INFO (payload): Payload Demo Initialized @@ -146,8 +134,7 @@ By default, Payload uses a mock implementation that only sends mail to the [ethe The mock email handler is used when payload is started with neither `transport` or `transportOptions` to know how to deliver email. - The randomly generated email account username and password will be different - each time the Payload server starts. + The randomly generated email account username and password will be different each time the Payload server starts. ### Using multiple mail providers diff --git a/docs/fields/array.mdx b/docs/fields/array.mdx index 0a312c75a3..d00ed02094 100644 --- a/docs/fields/array.mdx +++ b/docs/fields/array.mdx @@ -6,10 +6,8 @@ desc: Array fields are intended for sets of repeating fields, that you define. L keywords: array, fields, config, configuration, documentation, Content Management System, cms, headless, javascript, node, react, express --- - - The Array field type is used when you need to have a set of "repeating" - fields. It stores an array of objects containing the fields that you define. - Its uses can be simple or highly complex. + + The Array field type is used when you need to have a set of "repeating" fields. It stores an array of objects containing the fields that you define. Its uses can be simple or highly complex. **Example uses:** @@ -19,32 +17,31 @@ keywords: array, fields, config, configuration, documentation, Content Managemen - Event agenda "timeslots" where you need to specify start & end time ([date field](/docs/fields/date)), label ([text field](/docs/fields/text)), and Learn More page [relationship](/docs/fields/relationship) ![Array field in Payload admin panel](https://payloadcms.com/images/fields/array.jpg) -_Admin panel screenshot of an Array field with a Row containing two text fields, a read-only text field and a checkbox_ +*Admin panel screenshot of an Array field with a Row containing two text fields, a read-only text field and a checkbox* ### Config -| Option | Description | -| ------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| **`name`** \* | To be used as the property name when stored and retrieved from the database. | -| **`label`** | Used as a heading in the Admin panel and to name the generated GraphQL type. | -| **`fields`** \* | Array of field types to correspond to each row of the Array. | -| **`validate`** | Provide a custom validation function that will be executed on both the Admin panel and the backend. [More](/docs/fields/overview#validation) | -| **`saveToJWT`** | If this field is top-level and nested in a config supporting [Authentication](/docs/authentication/config), include its data in the user JWT. | -| **`hooks`** | Provide field-based hooks to control logic for this field. [More](/docs/fields/overview#field-level-hooks) | -| **`access`** | Provide field-based access control to denote what users can see and do with this field's data. [More](/docs/fields/overview#field-level-access-control) | -| **`hidden`** | Restrict this field's visibility from all APIs entirely. Will still be saved to the database, but will not appear in any API or the Admin panel. | -| **`defaultValue`** | Provide an array of row data to be used for this field's default value. | -| **`localized`** | Enable localization for this field. Requires [localization to be enabled](/docs/configuration/localization) in the Base config. If enabled, a separate, localized set of all data within this Array will be kept, so there is no need to specify each nested field as `localized`. | -| **`required`** | Require this field to have a value. | -| **`labels`** | Customize the row labels appearing in the Admin dashboard. | -| **`admin`** | Admin-specific configuration. See the [default field admin config](/docs/fields/overview#admin-config) for more details. | +| Option | Description | +| ---------------- | ----------- | +| **`name`** * | To be used as the property name when stored and retrieved from the database. | +| **`label`** | Used as a heading in the Admin panel and to name the generated GraphQL type. | +| **`fields`** * | Array of field types to correspond to each row of the Array. | +| **`validate`** | Provide a custom validation function that will be executed on both the Admin panel and the backend. [More](/docs/fields/overview#validation) | +| **`saveToJWT`** | If this field is top-level and nested in a config supporting [Authentication](/docs/authentication/config), include its data in the user JWT. | +| **`hooks`** | Provide field-based hooks to control logic for this field. [More](/docs/fields/overview#field-level-hooks) | +| **`access`** | Provide field-based access control to denote what users can see and do with this field's data. [More](/docs/fields/overview#field-level-access-control) | +| **`hidden`** | Restrict this field's visibility from all APIs entirely. Will still be saved to the database, but will not appear in any API or the Admin panel. | +| **`defaultValue`** | Provide an array of row data to be used for this field's default value. | +| **`localized`** | Enable localization for this field. Requires [localization to be enabled](/docs/configuration/localization) in the Base config. If enabled, a separate, localized set of all data within this Array will be kept, so there is no need to specify each nested field as `localized`. | +| **`required`** | Require this field to have a value. | +| **`labels`** | Customize the row labels appearing in the Admin dashboard. | +| **`admin`** | Admin-specific configuration. See the [default field admin config](/docs/fields/overview#admin-config) for more details. | -_\* An asterisk denotes that a property is required._ +*\* An asterisk denotes that a property is required.* ### Example `collections/ExampleCollection.js` - ```js { slug: 'example-collection', diff --git a/docs/fields/blocks.mdx b/docs/fields/blocks.mdx index fb62014909..f84f7dfb3b 100644 --- a/docs/fields/blocks.mdx +++ b/docs/fields/blocks.mdx @@ -6,11 +6,8 @@ desc: The Blocks field type is a great layout build and can be used to construct keywords: blocks, fields, config, configuration, documentation, Content Management System, cms, headless, javascript, node, react, express --- - - The Blocks field type is incredibly powerful and can be used - as a layout builder as well as to define any other flexible content - model you can think of. It stores an array of objects, where each object must - match the shape of one of your provided block configs. + + The Blocks field type is incredibly powerful and can be used as a layout builder as well as to define any other flexible content model you can think of. It stores an array of objects, where each object must match the shape of one of your provided block configs. **Example uses:** @@ -20,50 +17,45 @@ keywords: blocks, fields, config, configuration, documentation, Content Manageme - Virtual event agenda "timeslots" where a timeslot could either be a `Break`, a `Presentation`, or a `BreakoutSession`. ![Blocks field in Payload admin panel](https://payloadcms.com/images/fields/blocks.jpg) -_Admin panel screenshot of a Blocks field type with Call to Action and Number block examples_ +*Admin panel screenshot of a Blocks field type with Call to Action and Number block examples* + ### Field config -| Option | Description | -| ------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --- | -------------- | ----------------------------------- | -| **`name`** \* | To be used as the property name when stored and retrieved from the database. | -| **`label`** | Used as a heading in the Admin panel and to name the generated GraphQL type. | -| **`blocks`** \* | Array of [block configs](/docs/fields/blocks#block-configs) to be made available to this field. | -| **`validate`** | Provide a custom validation function that will be executed on both the Admin panel and the backend. [More](/docs/fields/overview#validation) | -| **`saveToJWT`** | If this field is top-level and nested in a config supporting [Authentication](/docs/authentication/config), include its data in the user JWT. | -| **`hooks`** | Provide field-level hooks to control logic for this field. [More](/docs/fields/overview#field-level-hooks) | -| **`access`** | Provide field-level access control to denote what users can see and do with this field's data. [More](/docs/fields/overview#field-level-access-control) | -| **`hidden`** | Restrict this field's visibility from all APIs entirely. Will still be saved to the database, but will not appear in any API response or the Admin panel. | -| **`defaultValue`** | Provide an array of block data to be used for this field's default value. | -| **`localized`** | Enable localization for this field. Requires [localization to be enabled](/docs/configuration/localization) in the Base config. If enabled, a separate, localized set of all data within this field will be kept, so there is no need to specify each nested field as `localized`. | | **`required`** | Require this field to have a value. | -| **`unique`** | Enforce that each entry in the Collection has a unique value for this field. | -| **`labels`** | Customize the block row labels appearing in the Admin dashboard. | -| **`admin`** | Admin-specific configuration. See the [default field admin config](/docs/fields/overview#admin-config) for more details. | +| Option | Description | +| ---------------- | ----------- | +| **`name`** * | To be used as the property name when stored and retrieved from the database. | +| **`label`** | Used as a heading in the Admin panel and to name the generated GraphQL type. | +| **`blocks`** * | Array of [block configs](/docs/fields/blocks#block-configs) to be made available to this field. | +| **`validate`** | Provide a custom validation function that will be executed on both the Admin panel and the backend. [More](/docs/fields/overview#validation) | +| **`saveToJWT`** | If this field is top-level and nested in a config supporting [Authentication](/docs/authentication/config), include its data in the user JWT. | +| **`hooks`** | Provide field-level hooks to control logic for this field. [More](/docs/fields/overview#field-level-hooks) | +| **`access`** | Provide field-level access control to denote what users can see and do with this field's data. [More](/docs/fields/overview#field-level-access-control) | +| **`hidden`** | Restrict this field's visibility from all APIs entirely. Will still be saved to the database, but will not appear in any API response or the Admin panel. | +| **`defaultValue`** | Provide an array of block data to be used for this field's default value. | +| **`localized`** | Enable localization for this field. Requires [localization to be enabled](/docs/configuration/localization) in the Base config. If enabled, a separate, localized set of all data within this field will be kept, so there is no need to specify each nested field as `localized`. || **`required`** | Require this field to have a value. | +| **`unique`** | Enforce that each entry in the Collection has a unique value for this field. | +| **`labels`** | Customize the block row labels appearing in the Admin dashboard. | +| **`admin`** | Admin-specific configuration. See the [default field admin config](/docs/fields/overview#admin-config) for more details. | -_\* An asterisk denotes that a property is required._ +*\* An asterisk denotes that a property is required.* ### Block configs Blocks are defined as separate configs of their own. - Tip: -
- Best practice is to define each block config in its own file, and then import - them into your Blocks field as necessary. This way each block config can be - easily shared between fields. For instance, using the "layout builder" - example, you might want to feature a few of the same blocks in a Post - collection as well as a Page collection. Abstracting into their own files - trivializes their reusability. + Tip:
+ Best practice is to define each block config in its own file, and then import them into your Blocks field as necessary. This way each block config can be easily shared between fields. For instance, using the "layout builder" example, you might want to feature a few of the same blocks in a Post collection as well as a Page collection. Abstracting into their own files trivializes their reusability.
-| Option | Description | -| ------------------ | -------------------------------------------------------------------------------------------------------------------- | -| **`slug`** \* | Identifier for this block type. Will be saved on each block as the `blockType` property. | -| **`fields`** \* | Array of fields to be stored in this block. | -| **`labels`** | Customize the block labels that appear in the Admin dashboard. Also used to name corresponding GraphQL schema types. | -| **`imageURL`** | Provide a custom image thumbnail to help editors identify this block in the Admin UI. | -| **`imageAltText`** | Customize this block's image thumbnail alt text. | +| Option | Description | +| ---------------- | ----------- | +| **`slug`** * | Identifier for this block type. Will be saved on each block as the `blockType` property. | +| **`fields`** * | Array of fields to be stored in this block. | +| **`labels`** | Customize the block labels that appear in the Admin dashboard. Also used to name corresponding GraphQL schema types. | +| **`imageURL`** | Provide a custom image thumbnail to help editors identify this block in the Admin UI. | +| **`imageAltText`** | Customize this block's image thumbnail alt text. | #### Auto-generated data per block @@ -80,46 +72,44 @@ The Admin panel provides each block with a `blockName` field which optionally al ### Example `collections/ExampleCollection.js` - ```js const QuoteBlock = { - slug: "Quote", // required - imageURL: "https://google.com/path/to/image.jpg", - imageAltText: "A nice thumbnail image to show what this block looks like", - fields: [ - // required + slug: 'Quote', // required + imageURL: 'https://google.com/path/to/image.jpg', + imageAltText: 'A nice thumbnail image to show what this block looks like', + fields: [ // required { - name: "text", - label: "Quote Text", - type: "text", + name: 'text', + label: 'Quote Text', + type: 'text', required: true, }, { - name: "text", - label: "Quotee", - type: "text", + name: 'text', + label: 'Quotee', + type: 'text', }, - ], + ] }; const ExampleCollection = { - slug: "example-collection", + slug: 'example-collection', fields: [ { - name: "layout", // required - type: "blocks", // required - label: "layout", + name: 'layout', // required + type: 'blocks', // required + label: 'layout', minRows: 1, maxRows: 20, labels: { - singular: "Layout", - plural: "Layouts", + singular: 'Layout', + plural: 'Layouts', }, - blocks: [ - // required - QuoteBlock, - ], - }, - ], -}; + blocks: [ // required + QuoteBlock + ] + } + ] +} + ``` diff --git a/docs/fields/checkbox.mdx b/docs/fields/checkbox.mdx index f9c3f3c307..621c97b94e 100644 --- a/docs/fields/checkbox.mdx +++ b/docs/fields/checkbox.mdx @@ -6,31 +6,32 @@ desc: Checkbox field types allow the developer to save a boolean value in the da keywords: checkbox, fields, config, configuration, documentation, Content Management System, cms, headless, javascript, node, react, express --- -The Checkbox field type saves a boolean in the database. + + The Checkbox field type saves a boolean in the database. + ### Config -| Option | Description | -| ------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| **`name`** \* | To be used as the property name when stored and retrieved from the database. | -| **`label`** | Used as a field label in the Admin panel and to name the generated GraphQL type. | -| **`validate`** | Provide a custom validation function that will be executed on both the Admin panel and the backend. [More](/docs/fields/overview#validation) | -| **`index`** | Build a [MongoDB index](https://docs.mongodb.com/manual/indexes/) for this field to produce faster queries. Set this field to `true` if your users will perform queries on this field's data often. | -| **`saveToJWT`** | If this field is top-level and nested in a config supporting [Authentication](/docs/authentication/config), include its data in the user JWT. | -| **`hooks`** | Provide field-based hooks to control logic for this field. [More](/docs/fields/overview#field-level-hooks) | -| **`access`** | Provide field-based access control to denote what users can see and do with this field's data. [More](/docs/fields/overview#field-level-access-control) | -| **`hidden`** | Restrict this field's visibility from all APIs entirely. Will still be saved to the database, but will not appear in any API or the Admin panel. | -| **`defaultValue`** | Provide data to be used for this field's default value. | -| **`localized`** | Enable localization for this field. Requires [localization to be enabled](/docs/configuration/localization) in the Base config. | -| **`required`** | Require this field to have a value. | -| **`admin`** | Admin-specific configuration. See the [default field admin config](/docs/fields/overview#admin-config) for more details. | +| Option | Description | +| ---------------- | ----------- | +| **`name`** * | To be used as the property name when stored and retrieved from the database. | +| **`label`** | Used as a field label in the Admin panel and to name the generated GraphQL type. | +| **`validate`** | Provide a custom validation function that will be executed on both the Admin panel and the backend. [More](/docs/fields/overview#validation) | +| **`index`** | Build a [MongoDB index](https://docs.mongodb.com/manual/indexes/) for this field to produce faster queries. Set this field to `true` if your users will perform queries on this field's data often. | +| **`saveToJWT`** | If this field is top-level and nested in a config supporting [Authentication](/docs/authentication/config), include its data in the user JWT. | +| **`hooks`** | Provide field-based hooks to control logic for this field. [More](/docs/fields/overview#field-level-hooks) | +| **`access`** | Provide field-based access control to denote what users can see and do with this field's data. [More](/docs/fields/overview#field-level-access-control) | +| **`hidden`** | Restrict this field's visibility from all APIs entirely. Will still be saved to the database, but will not appear in any API or the Admin panel. | +| **`defaultValue`** | Provide data to be used for this field's default value. | +| **`localized`** | Enable localization for this field. Requires [localization to be enabled](/docs/configuration/localization) in the Base config. | +| **`required`** | Require this field to have a value. | +| **`admin`** | Admin-specific configuration. See the [default field admin config](/docs/fields/overview#admin-config) for more details. | -_\* An asterisk denotes that a property is required._ +*\* An asterisk denotes that a property is required.* ### Example `collections/ExampleCollection.js` - ```js { slug: 'example-collection', diff --git a/docs/fields/code.mdx b/docs/fields/code.mdx index e4bc26b8aa..67ad38a2fa 100644 --- a/docs/fields/code.mdx +++ b/docs/fields/code.mdx @@ -7,34 +7,33 @@ desc: The Code field type will store any string in the Database. Learn how to us keywords: code, fields, config, configuration, documentation, Content Management System, cms, headless, javascript, node, react, express --- - - The Code field type saves a string in the database, but provides the Admin - panel with a code editor styled interface. + + The Code field type saves a string in the database, but provides the Admin panel with a code editor styled interface. This field uses `prismjs` for syntax highlighting and `react-simple-code-editor` for the editor itself. ### Config -| Option | Description | -| ------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| **`name`** \* | To be used as the property name when stored and retrieved from the database. | -| **`label`** | Used as a field label in the Admin panel and to name the generated GraphQL type. | -| **`unique`** | Enforce that each entry in the Collection has a unique value for this field. | -| **`index`** | Build a [MongoDB index](https://docs.mongodb.com/manual/indexes/) for this field to produce faster queries. Set this field to `true` if your users will perform queries on this field's data often. | -| **`minLength`** | Used by the default validation function to ensure values are of a minimum character length. | -| **`maxLength`** | Used by the default validation function to ensure values are of a maximum character length. | -| **`validate`** | Provide a custom validation function that will be executed on both the Admin panel and the backend. [More](/docs/fields/overview#validation) | -| **`saveToJWT`** | If this field is top-level and nested in a config supporting [Authentication](/docs/authentication/config), include its data in the user JWT. | -| **`hooks`** | Provide field-based hooks to control logic for this field. [More](/docs/fields/overview#field-level-hooks) | -| **`access`** | Provide field-based access control to denote what users can see and do with this field's data. [More](/docs/fields/overview#field-level-access-control) | -| **`hidden`** | Restrict this field's visibility from all APIs entirely. Will still be saved to the database, but will not appear in any API or the Admin panel. | -| **`defaultValue`** | Provide data to be used for this field's default value. | -| **`localized`** | Enable localization for this field. Requires [localization to be enabled](/docs/configuration/localization) in the Base config. | -| **`required`** | Require this field to have a value. | -| **`admin`** | Admin-specific configuration. See below for [more detail](#admin-config). | +| Option | Description | +| ---------------- | ----------- | +| **`name`** * | To be used as the property name when stored and retrieved from the database. | +| **`label`** | Used as a field label in the Admin panel and to name the generated GraphQL type. | +| **`unique`** | Enforce that each entry in the Collection has a unique value for this field. | +| **`index`** | Build a [MongoDB index](https://docs.mongodb.com/manual/indexes/) for this field to produce faster queries. Set this field to `true` if your users will perform queries on this field's data often. | +| **`minLength`** | Used by the default validation function to ensure values are of a minimum character length. | +| **`maxLength`** | Used by the default validation function to ensure values are of a maximum character length. | +| **`validate`** | Provide a custom validation function that will be executed on both the Admin panel and the backend. [More](/docs/fields/overview#validation) | +| **`saveToJWT`** | If this field is top-level and nested in a config supporting [Authentication](/docs/authentication/config), include its data in the user JWT. | +| **`hooks`** | Provide field-based hooks to control logic for this field. [More](/docs/fields/overview#field-level-hooks) | +| **`access`** | Provide field-based access control to denote what users can see and do with this field's data. [More](/docs/fields/overview#field-level-access-control) | +| **`hidden`** | Restrict this field's visibility from all APIs entirely. Will still be saved to the database, but will not appear in any API or the Admin panel. | +| **`defaultValue`** | Provide data to be used for this field's default value. | +| **`localized`** | Enable localization for this field. Requires [localization to be enabled](/docs/configuration/localization) in the Base config. | +| **`required`** | Require this field to have a value. | +| **`admin`** | Admin-specific configuration. See below for [more detail](#admin-config). | -_\* An asterisk denotes that a property is required._ +*\* An asterisk denotes that a property is required.* ### Admin config @@ -45,7 +44,6 @@ Currently, the `language` property only supports JavaScript syntax but more supp ### Example `collections/ExampleCollection.js` - ```js { slug: 'example-collection', diff --git a/docs/fields/date.mdx b/docs/fields/date.mdx index 5b371d4027..5ae80413d4 100644 --- a/docs/fields/date.mdx +++ b/docs/fields/date.mdx @@ -6,31 +6,30 @@ desc: The Date field type stores a Date in the database. Learn how to use and cu keywords: date, fields, config, configuration, documentation, Content Management System, cms, headless, javascript, node, react, express --- - - The Date field type saves a Date in the database and provides the Admin panel - with a customizable time picker interface. + + The Date field type saves a Date in the database and provides the Admin panel with a customizable time picker interface. This field uses [`react-datepicker`](https://www.npmjs.com/package/react-datepicker) for the Admin panel component. ### Config -| Option | Description | -| ------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| **`name`** \* | To be used as the property name when stored and retrieved from the database. | -| **`label`** | Used as a field label in the Admin panel and to name the generated GraphQL type. | -| **`index`** | Build a [MongoDB index](https://docs.mongodb.com/manual/indexes/) for this field to produce faster queries. Set this field to `true` if your users will perform queries on this field's data often. | -| **`validate`** | Provide a custom validation function that will be executed on both the Admin panel and the backend. [More](/docs/fields/overview#validation) | -| **`saveToJWT`** | If this field is top-level and nested in a config supporting [Authentication](/docs/authentication/config), include its data in the user JWT. | -| **`hooks`** | Provide field-based hooks to control logic for this field. [More](/docs/fields/overview#field-level-hooks) | -| **`access`** | Provide field-based access control to denote what users can see and do with this field's data. [More](/docs/fields/overview#field-level-access-control) | -| **`hidden`** | Restrict this field's visibility from all APIs entirely. Will still be saved to the database, but will not appear in any API or the Admin panel. | -| **`defaultValue`** | Provide data to be used for this field's default value. | -| **`localized`** | Enable localization for this field. Requires [localization to be enabled](/docs/configuration/localization) in the Base config. | -| **`required`** | Require this field to have a value. | -| **`admin`** | Admin-specific configuration. See below for [more detail](#admin). | +| Option | Description | +| ---------------- | ----------- | +| **`name`** * | To be used as the property name when stored and retrieved from the database. | +| **`label`** | Used as a field label in the Admin panel and to name the generated GraphQL type. | +| **`index`** | Build a [MongoDB index](https://docs.mongodb.com/manual/indexes/) for this field to produce faster queries. Set this field to `true` if your users will perform queries on this field's data often. | +| **`validate`** | Provide a custom validation function that will be executed on both the Admin panel and the backend. [More](/docs/fields/overview#validation) | +| **`saveToJWT`** | If this field is top-level and nested in a config supporting [Authentication](/docs/authentication/config), include its data in the user JWT. | +| **`hooks`** | Provide field-based hooks to control logic for this field. [More](/docs/fields/overview#field-level-hooks) | +| **`access`** | Provide field-based access control to denote what users can see and do with this field's data. [More](/docs/fields/overview#field-level-access-control) | +| **`hidden`** | Restrict this field's visibility from all APIs entirely. Will still be saved to the database, but will not appear in any API or the Admin panel. | +| **`defaultValue`** | Provide data to be used for this field's default value. | +| **`localized`** | Enable localization for this field. Requires [localization to be enabled](/docs/configuration/localization) in the Base config. | +| **`required`** | Require this field to have a value. | +| **`admin`** | Admin-specific configuration. See below for [more detail](#admin). | -_\* An asterisk denotes that a property is required._ +*\* An asterisk denotes that a property is required.* ### Admin config @@ -43,7 +42,6 @@ Common use cases for customizing the `date` property are to restrict your field ### Example `collections/ExampleCollection.js` - ```js { slug: 'example-collection', diff --git a/docs/fields/email.mdx b/docs/fields/email.mdx index 1e155a26bf..f4fd1cc6f9 100644 --- a/docs/fields/email.mdx +++ b/docs/fields/email.mdx @@ -6,29 +6,29 @@ desc: The Email field enforces that the value provided is a valid email address. keywords: email, fields, config, configuration, documentation, Content Management System, cms, headless, javascript, node, react, express --- - + The Email field enforces that the value provided is a valid email address. ### Config -| Option | Description | -| ------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| **`name`** \* | To be used as the property name when stored and retrieved from the database. | -| **`label`** | Used as a field label in the Admin panel and to name the generated GraphQL type. | -| **`unique`** | Enforce that each entry in the Collection has a unique value for this field. | -| **`index`** | Build a [MongoDB index](https://docs.mongodb.com/manual/indexes/) for this field to produce faster queries. Set this field to `true` if your users will perform queries on this field's data often. | -| **`validate`** | Provide a custom validation function that will be executed on both the Admin panel and the backend. [More](/docs/fields/overview#validation) | -| **`saveToJWT`** | If this field is top-level and nested in a config supporting [Authentication](/docs/authentication/config), include its data in the user JWT. | -| **`hooks`** | Provide field-based hooks to control logic for this field. [More](/docs/fields/overview#field-level-hooks) | -| **`access`** | Provide field-based access control to denote what users can see and do with this field's data. [More](/docs/fields/overview#field-level-access-control) | -| **`hidden`** | Restrict this field's visibility from all APIs entirely. Will still be saved to the database, but will not appear in any API or the Admin panel. | -| **`defaultValue`** | Provide data to be used for this field's default value. | -| **`localized`** | Enable localization for this field. Requires [localization to be enabled](/docs/configuration/localization) in the Base config. | -| **`required`** | Require this field to have a value. | -| **`admin`** | Admin-specific configuration. See below for [more detail](#admin). | +| Option | Description | +| ---------------- | ----------- | +| **`name`** * | To be used as the property name when stored and retrieved from the database. | +| **`label`** | Used as a field label in the Admin panel and to name the generated GraphQL type. | +| **`unique`** | Enforce that each entry in the Collection has a unique value for this field. | +| **`index`** | Build a [MongoDB index](https://docs.mongodb.com/manual/indexes/) for this field to produce faster queries. Set this field to `true` if your users will perform queries on this field's data often. | +| **`validate`** | Provide a custom validation function that will be executed on both the Admin panel and the backend. [More](/docs/fields/overview#validation) | +| **`saveToJWT`** | If this field is top-level and nested in a config supporting [Authentication](/docs/authentication/config), include its data in the user JWT. | +| **`hooks`** | Provide field-based hooks to control logic for this field. [More](/docs/fields/overview#field-level-hooks) | +| **`access`** | Provide field-based access control to denote what users can see and do with this field's data. [More](/docs/fields/overview#field-level-access-control) | +| **`hidden`** | Restrict this field's visibility from all APIs entirely. Will still be saved to the database, but will not appear in any API or the Admin panel. | +| **`defaultValue`** | Provide data to be used for this field's default value. | +| **`localized`** | Enable localization for this field. Requires [localization to be enabled](/docs/configuration/localization) in the Base config. | +| **`required`** | Require this field to have a value. | +| **`admin`** | Admin-specific configuration. See below for [more detail](#admin). | -_\* An asterisk denotes that a property is required._ +*\* An asterisk denotes that a property is required.* ### Admin config @@ -45,7 +45,6 @@ Set this property to a string that will be used for browser autocomplete. ### Example `collections/ExampleCollection.js` - ```js { slug: 'example-collection', diff --git a/docs/fields/group.mdx b/docs/fields/group.mdx index 8bcf9aa12f..5ff7b1fa81 100644 --- a/docs/fields/group.mdx +++ b/docs/fields/group.mdx @@ -6,34 +6,32 @@ desc: The Group field allows other fields to be nested under a common property. keywords: group, fields, config, configuration, documentation, Content Management System, cms, headless, javascript, node, react, express --- - - The Group field allows fields to be nested under a common property name. It - also groups fields together visually in the Admin panel. + + The Group field allows fields to be nested under a common property name. It also groups fields together visually in the Admin panel. ### Config -| Option | Description | -| ------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| **`name`** \* | To be used as the property name when stored and retrieved from the database. | -| **`fields`** \* | Array of field types to nest within this Group. | -| **`label`** | Used as a heading in the Admin panel and to name the generated GraphQL type. | -| **`validate`** | Provide a custom validation function that will be executed on both the Admin panel and the backend. [More](/docs/fields/overview#validation) | -| **`saveToJWT`** | If this field is top-level and nested in a config supporting [Authentication](/docs/authentication/config), include its data in the user JWT. | -| **`hooks`** | Provide field-based hooks to control logic for this field. [More](/docs/fields/overview#field-level-hooks) | -| **`access`** | Provide field-based access control to denote what users can see and do with this field's data. [More](/docs/fields/overview#field-level-access-control) | -| **`hidden`** | Restrict this field's visibility from all APIs entirely. Will still be saved to the database, but will not appear in any API or the Admin panel. | -| **`defaultValue`** | Provide an object of data to be used for this field's default value. | -| **`localized`** | Enable localization for this field. Requires [localization to be enabled](/docs/configuration/localization) in the Base config. If enabled, a separate, localized set of all data within this Group will be kept, so there is no need to specify each nested field as `localized`. | -| **`required`** | Require this field to have a value. | -| **`admin`** | Admin-specific configuration. See the [default field admin config](/docs/fields/overview#admin-config) for more details. | +| Option | Description | +| ---------------- | ----------- | +| **`name`** * | To be used as the property name when stored and retrieved from the database. | +| **`fields`** * | Array of field types to nest within this Group. | +| **`label`** | Used as a heading in the Admin panel and to name the generated GraphQL type. | +| **`validate`** | Provide a custom validation function that will be executed on both the Admin panel and the backend. [More](/docs/fields/overview#validation) | +| **`saveToJWT`** | If this field is top-level and nested in a config supporting [Authentication](/docs/authentication/config), include its data in the user JWT. | +| **`hooks`** | Provide field-based hooks to control logic for this field. [More](/docs/fields/overview#field-level-hooks) | +| **`access`** | Provide field-based access control to denote what users can see and do with this field's data. [More](/docs/fields/overview#field-level-access-control) | +| **`hidden`** | Restrict this field's visibility from all APIs entirely. Will still be saved to the database, but will not appear in any API or the Admin panel. | +| **`defaultValue`** | Provide an object of data to be used for this field's default value. | +| **`localized`** | Enable localization for this field. Requires [localization to be enabled](/docs/configuration/localization) in the Base config. If enabled, a separate, localized set of all data within this Group will be kept, so there is no need to specify each nested field as `localized`. | +| **`required`** | Require this field to have a value. | +| **`admin`** | Admin-specific configuration. See the [default field admin config](/docs/fields/overview#admin-config) for more details. | -_\* An asterisk denotes that a property is required._ +*\* An asterisk denotes that a property is required.* ### Example `collections/ExampleCollection.js` - ```js { slug: 'example-collection', diff --git a/docs/fields/number.mdx b/docs/fields/number.mdx index e44313405f..1b9d1dd245 100644 --- a/docs/fields/number.mdx +++ b/docs/fields/number.mdx @@ -6,32 +6,31 @@ desc: Number fields store and validate numeric data. Learn how to use and format keywords: number, fields, config, configuration, documentation, Content Management System, cms, headless, javascript, node, react, express --- - - The Number field stores and validates numeric entry and supports additional - numerical validation and formatting features. + + The Number field stores and validates numeric entry and supports additional numerical validation and formatting features. ### Config -| Option | Description | -| ------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| **`name`** \* | To be used as the property name when stored and retrieved from the database. | -| **`label`** | Used as a field label in the Admin panel and to name the generated GraphQL type. | -| **`min`** | Minimum value accepted. Used in the default `validation` function. | -| **`max`** | Maximum value accepted. Used in the default `validation` function. | -| **`unique`** | Enforce that each entry in the Collection has a unique value for this field. | -| **`index`** | Build a [MongoDB index](https://docs.mongodb.com/manual/indexes/) for this field to produce faster queries. Set this field to `true` if your users will perform queries on this field's data often. | -| **`validate`** | Provide a custom validation function that will be executed on both the Admin panel and the backend. [More](/docs/fields/overview#validation) | -| **`saveToJWT`** | If this field is top-level and nested in a config supporting [Authentication](/docs/authentication/config), include its data in the user JWT. | -| **`hooks`** | Provide field-based hooks to control logic for this field. [More](/docs/fields/overview#field-level-hooks) | -| **`access`** | Provide field-based access control to denote what users can see and do with this field's data. [More](/docs/fields/overview#field-level-access-control) | -| **`hidden`** | Restrict this field's visibility from all APIs entirely. Will still be saved to the database, but will not appear in any API or the Admin panel. | -| **`defaultValue`** | Provide data to be used for this field's default value. | -| **`localized`** | Enable localization for this field. Requires [localization to be enabled](/docs/configuration/localization) in the Base config. | -| **`required`** | Require this field to have a value. | -| **`admin`** | Admin-specific configuration. See below for [more detail](#admin). | +| Option | Description | +| ---------------- | ----------- | +| **`name`** * | To be used as the property name when stored and retrieved from the database. | +| **`label`** | Used as a field label in the Admin panel and to name the generated GraphQL type. | +| **`min`** | Minimum value accepted. Used in the default `validation` function. | +| **`max`** | Maximum value accepted. Used in the default `validation` function. | +| **`unique`** | Enforce that each entry in the Collection has a unique value for this field. | +| **`index`** | Build a [MongoDB index](https://docs.mongodb.com/manual/indexes/) for this field to produce faster queries. Set this field to `true` if your users will perform queries on this field's data often. | +| **`validate`** | Provide a custom validation function that will be executed on both the Admin panel and the backend. [More](/docs/fields/overview#validation) | +| **`saveToJWT`** | If this field is top-level and nested in a config supporting [Authentication](/docs/authentication/config), include its data in the user JWT. | +| **`hooks`** | Provide field-based hooks to control logic for this field. [More](/docs/fields/overview#field-level-hooks) | +| **`access`** | Provide field-based access control to denote what users can see and do with this field's data. [More](/docs/fields/overview#field-level-access-control) | +| **`hidden`** | Restrict this field's visibility from all APIs entirely. Will still be saved to the database, but will not appear in any API or the Admin panel. | +| **`defaultValue`** | Provide data to be used for this field's default value. | +| **`localized`** | Enable localization for this field. Requires [localization to be enabled](/docs/configuration/localization) in the Base config. | +| **`required`** | Require this field to have a value. | +| **`admin`** | Admin-specific configuration. See below for [more detail](#admin). | -_\* An asterisk denotes that a property is required._ +*\* An asterisk denotes that a property is required.* ### Admin config @@ -52,7 +51,6 @@ Set this property to a string that will be used for browser autocomplete. ### Example `collections/ExampleCollection.js` - ```js { slug: 'example-collection', diff --git a/docs/fields/overview.mdx b/docs/fields/overview.mdx index ffc791f4f7..858f15d8f4 100644 --- a/docs/fields/overview.mdx +++ b/docs/fields/overview.mdx @@ -7,9 +7,7 @@ keywords: overview, fields, config, configuration, documentation, Content Manage --- - Fields are the building blocks of Payload. Collections and Globals both use - Fields to define the shape of the data that they store. Payload offers a wide - variety of field types - both simple and complex. + Fields are the building blocks of Payload. Collections and Globals both use Fields to define the shape of the data that they store. Payload offers a wide variety of field types - both simple and complex. Fields are defined as an array on Collections and Globals via the `fields` key. They define the shape of the data that will be stored as well as automatically construct the corresponding Admin UI. @@ -17,23 +15,22 @@ Fields are defined as an array on Collections and Globals via the `fields` key. The required `type` property on a field determines what values it can accept, how it is presented in the API, and how the field will be rendered in the admin interface. **Simple collection with two fields:** - ```js const Pages = { - slug: "pages", - fields: [ - { - name: "my-field", - type: "text", // highlight-line - label: "My Field", - }, - { - name: "other-field", - type: "checkbox", // highlight-line - label: "Other Field", - }, - ], -}; + slug: 'pages', + fields: [ + { + name: 'my-field', + type: 'text', // highlight-line + label: 'My Field', + }, + { + name: 'other-field', + type: 'checkbox', // highlight-line + label: 'Other Field' + }, + ], +} ``` ### Field types @@ -68,7 +65,6 @@ In addition to being able to define access control on a document-level, you can You can provide your own validation function for all field types. It will be used on both the frontend and the backend, so it should not rely on any Node-specific packages. The validation function can be either synchronous or asynchronous and accepts the field's value and expects to return either `true` or a string error message to display in both API responses and within the Admin panel. Example: - ```js { slug: 'orders', @@ -93,15 +89,15 @@ Example: In addition to each field's base configuration, you can define specific traits and properties for fields that only have effect on how they are rendered in the Admin panel. The following properties are available for all fields within the `admin` property: -| Option | Description | -| ------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `condition` | You can programmatically show / hide fields based on what other fields are doing. [Click here](#conditional-logic) for more info. | -| `components` | All field components can be completely and easily swapped out for custom components that you define. [Click here](#custom-admin-components) for more info. | -| `position` | Specify if the field should be rendered in the sidebar by defining `position: 'sidebar'`. | -| `width` | Restrict the width of a field. you can pass any string-based value here, be it pixels, percentages, etc. This property is especially useful when fields are nested within a `Row` type where they can be organized horizontally. | -| `readOnly` | Setting a field to `readOnly` has no effect on the API whatsoever but disables the admin component's editability to prevent editors from modifying the field's value. | -| `disabled` | If a field is `disabled`, it is completely omitted from the Admin panel. | -| `hidden` | Setting a field's `hidden` property on its `admin` config will transform it into a `hidden` input type. Its value will still submit with the Admin panel's requests, but the field itself will not be visible to editors. | +| Option | Description | +| ------------- | -------------| +| `condition` | You can programmatically show / hide fields based on what other fields are doing. [Click here](#conditional-logic) for more info. | +| `components` | All field components can be completely and easily swapped out for custom components that you define. [Click here](#custom-admin-components) for more info. | +| `position` | Specify if the field should be rendered in the sidebar by defining `position: 'sidebar'`. | +| `width` | Restrict the width of a field. you can pass any string-based value here, be it pixels, percentages, etc. This property is especially useful when fields are nested within a `Row` type where they can be organized horizontally. | +| `readOnly` | Setting a field to `readOnly` has no effect on the API whatsoever but disables the admin component's editability to prevent editors from modifying the field's value. | +| `disabled` | If a field is `disabled`, it is completely omitted from the Admin panel. | +| `hidden` | Setting a field's `hidden` property on its `admin` config will transform it into a `hidden` input type. Its value will still submit with the Admin panel's requests, but the field itself will not be visible to editors. | ### Conditional logic @@ -118,13 +114,13 @@ The `condition` function should return a boolean that will control if the field { fields: [ { - name: "enableGreeting", - type: "checkbox", + name: 'enableGreeting', + type: 'checkbox', defaultValue: false, }, { - name: "greeting", - type: "text", + name: 'greeting', + type: 'text', admin: { // highlight-start condition: (data, siblingData) => { @@ -133,11 +129,11 @@ The `condition` function should return a boolean that will control if the field } else { return false; } - }, + } // highlight-end - }, - }, - ]; + } + } + ] } ``` diff --git a/docs/fields/radio.mdx b/docs/fields/radio.mdx index 6cdbc9babd..b5684a9ea6 100644 --- a/docs/fields/radio.mdx +++ b/docs/fields/radio.mdx @@ -6,40 +6,33 @@ desc: The Radio field type allows for the selection of one value from a predefin keywords: radio, fields, config, configuration, documentation, Content Management System, cms, headless, javascript, node, react, express --- - - The Radio field type allows for the selection of one value from a predefined - set of possible values and presents a radio group-style set of inputs to the - Admin panel. + + The Radio field type allows for the selection of one value from a predefined set of possible values and presents a radio group-style set of inputs to the Admin panel. ### Config -| Option | Description | -| ------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| **`name`** \* | To be used as the property name when stored and retrieved from the database. | -| **`options`** \* | Array of options to allow the field to store. Can either be an array of strings, or an array of objects containing an `option` string and a `value` string. | -| **`label`** | Used as a field label in the Admin panel and to name the generated GraphQL type. | -| **`validate`** | Provide a custom validation function that will be executed on both the Admin panel and the backend. [More](/docs/fields/overview#validation) | -| **`index`** | Build a [MongoDB index](https://docs.mongodb.com/manual/indexes/) for this field to produce faster queries. Set this field to `true` if your users will perform queries on this field's data often. | -| **`saveToJWT`** | If this field is top-level and nested in a config supporting [Authentication](/docs/authentication/config), include its data in the user JWT. | -| **`hooks`** | Provide field-based hooks to control logic for this field. [More](/docs/fields/overview#field-level-hooks) | -| **`access`** | Provide field-based access control to denote what users can see and do with this field's data. [More](/docs/fields/overview#field-level-access-control) | -| **`hidden`** | Restrict this field's visibility from all APIs entirely. Will still be saved to the database, but will not appear in any API or the Admin panel. | -| **`defaultValue`** | Provide data to be used for this field's default value. | -| **`localized`** | Enable localization for this field. Requires [localization to be enabled](/docs/configuration/localization) in the Base config. | -| **`required`** | Require this field to have a value. | -| **`admin`** | Admin-specific configuration. See below for [more detail](#admin). | +| Option | Description | +| ---------------- | ----------- | +| **`name`** * | To be used as the property name when stored and retrieved from the database. | +| **`options`** * | Array of options to allow the field to store. Can either be an array of strings, or an array of objects containing an `option` string and a `value` string. | +| **`label`** | Used as a field label in the Admin panel and to name the generated GraphQL type. | +| **`validate`** | Provide a custom validation function that will be executed on both the Admin panel and the backend. [More](/docs/fields/overview#validation) | +| **`index`** | Build a [MongoDB index](https://docs.mongodb.com/manual/indexes/) for this field to produce faster queries. Set this field to `true` if your users will perform queries on this field's data often. | +| **`saveToJWT`** | If this field is top-level and nested in a config supporting [Authentication](/docs/authentication/config), include its data in the user JWT. | +| **`hooks`** | Provide field-based hooks to control logic for this field. [More](/docs/fields/overview#field-level-hooks) | +| **`access`** | Provide field-based access control to denote what users can see and do with this field's data. [More](/docs/fields/overview#field-level-access-control) | +| **`hidden`** | Restrict this field's visibility from all APIs entirely. Will still be saved to the database, but will not appear in any API or the Admin panel. | +| **`defaultValue`** | Provide data to be used for this field's default value. | +| **`localized`** | Enable localization for this field. Requires [localization to be enabled](/docs/configuration/localization) in the Base config. | +| **`required`** | Require this field to have a value. | +| **`admin`** | Admin-specific configuration. See below for [more detail](#admin). | -_\* An asterisk denotes that a property is required._ +*\* An asterisk denotes that a property is required.* - Important: -
- Option values should be strings that do not contain hyphens or special - characters due to GraphQL enumeration naming constraints. Underscores are - allowed. If you determine you need your option values to be non-strings or - contain special characters, they will be formatted accordingly before being - used as a GraphQL enum. + Important:
+ Option values should be strings that do not contain hyphens or special characters due to GraphQL enumeration naming constraints. Underscores are allowed. If you determine you need your option values to be non-strings or contain special characters, they will be formatted accordingly before being used as a GraphQL enum.
### Admin config @@ -53,7 +46,6 @@ The `layout` property allows for the radio group to be styled as a horizonally o ### Example `collections/ExampleCollection.js` - ```js { slug: 'example-collection', diff --git a/docs/fields/relationship.mdx b/docs/fields/relationship.mdx index f40d3b4ed7..442094c7f9 100644 --- a/docs/fields/relationship.mdx +++ b/docs/fields/relationship.mdx @@ -6,9 +6,8 @@ desc: The Relationship field provides the ability to relate documents together. keywords: relationship, fields, config, configuration, documentation, Content Management System, cms, headless, javascript, node, react, express --- - - The Relationship field is one of the most powerful fields Payload features. It - provides for the ability to easily relate documents together. + + The Relationship field is one of the most powerful fields Payload features. It provides for the ability to easily relate documents together. **Example uses:** @@ -19,37 +18,34 @@ keywords: relationship, fields, config, configuration, documentation, Content Ma ### Config -| Option | Description | -| -------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| **`name`** \* | To be used as the property name when stored and retrieved from the database. | -| **`*relationTo`** \* | Provide one or many collection `slug`s to be able to assign relationships to. | -| **`hasMany`** | Boolean when, if set to `true`, allows this field to have many relations instead of only one. | -| **`label`** | Used as a field label in the Admin panel and to name the generated GraphQL type. | -| **`unique`** | Enforce that each entry in the Collection has a unique value for this field. | -| **`validate`** | Provide a custom validation function that will be executed on both the Admin panel and the backend. [More](/docs/fields/overview#validation) | +| Option | Description | +| ---------------- | ----------- | +| **`name`** * | To be used as the property name when stored and retrieved from the database. | +| **`*relationTo`** * | Provide one or many collection `slug`s to be able to assign relationships to. | +| **`hasMany`** | Boolean when, if set to `true`, allows this field to have many relations instead of only one. | +| **`label`** | Used as a field label in the Admin panel and to name the generated GraphQL type. | +| **`unique`** | Enforce that each entry in the Collection has a unique value for this field. | +| **`validate`** | Provide a custom validation function that will be executed on both the Admin panel and the backend. [More](/docs/fields/overview#validation) | | **`index`** | Build a [MongoDB index](https://docs.mongodb.com/manual/indexes/) for this field to produce faster queries. Set this field to `true` if your users will perform queries on this field's data often. | -| **`saveToJWT`** | If this field is top-level and nested in a config supporting [Authentication](/docs/authentication/config), include its data in the user JWT. | -| **`hooks`** | Provide field-based hooks to control logic for this field. [More](/docs/fields/overview#field-level-hooks) | -| **`access`** | Provide field-based access control to denote what users can see and do with this field's data. [More](/docs/fields/overview#field-level-access-control) | -| **`hidden`** | Restrict this field's visibility from all APIs entirely. Will still be saved to the database, but will not appear in any API or the Admin panel. | -| **`defaultValue`** | Provide data to be used for this field's default value. | -| **`localized`** | Enable localization for this field. Requires [localization to be enabled](/docs/configuration/localization) in the Base config. | -| **`required`** | Require this field to have a value. | -| **`admin`** | Admin-specific configuration. See the [default field admin config](/docs/fields/overview#admin-config) for more details. | +| **`saveToJWT`** | If this field is top-level and nested in a config supporting [Authentication](/docs/authentication/config), include its data in the user JWT. | +| **`hooks`** | Provide field-based hooks to control logic for this field. [More](/docs/fields/overview#field-level-hooks) | +| **`access`** | Provide field-based access control to denote what users can see and do with this field's data. [More](/docs/fields/overview#field-level-access-control) | +| **`hidden`** | Restrict this field's visibility from all APIs entirely. Will still be saved to the database, but will not appear in any API or the Admin panel. | +| **`defaultValue`** | Provide data to be used for this field's default value. | +| **`localized`** | Enable localization for this field. Requires [localization to be enabled](/docs/configuration/localization) in the Base config. | +| **`required`** | Require this field to have a value. | +| **`admin`** | Admin-specific configuration. See the [default field admin config](/docs/fields/overview#admin-config) for more details. | -_\* An asterisk denotes that a property is required._ +*\* An asterisk denotes that a property is required.* - Tip: -
- The Depth parameter can be - used to automatically populate related documents that are returned by the API. + Tip:
+ The Depth parameter can be used to automatically populate related documents that are returned by the API.
### Example `collections/ExampleCollection.js` - ```js { slug: 'example-collection', diff --git a/docs/fields/rich-text.mdx b/docs/fields/rich-text.mdx index a733589d0d..dfec1448d5 100644 --- a/docs/fields/rich-text.mdx +++ b/docs/fields/rich-text.mdx @@ -6,42 +6,33 @@ desc: The Rich Text field allows dynamic content to be written through the Admin keywords: rich text, fields, config, configuration, documentation, Content Management System, cms, headless, javascript, node, react, express --- - - The Rich Text field is a powerful way to allow editors to write dynamic - content. The content is saved as JSON in the database and can be converted - into any format, including HTML, that you need. + + The Rich Text field is a powerful way to allow editors to write dynamic content. The content is saved as JSON in the database and can be converted into any format, including HTML, that you need. The Admin component is built on the powerful [`slatejs`](https://docs.slatejs.org/) editor and is meant to be as extensible and customizable as possible. - - Consistent with Payload's goal of making you learn as litle of Payload as - possible, customizing and using the Rich Text Editor does not involve - learning how to develop for a Payload rich text editor. - {" "} - Instead, you can invest your time and effort into learning Slate, an - open-source tool that will allow you to apply your learnings elsewhere as - well. + Consistent with Payload's goal of making you learn as litle of Payload as possible, customizing and using the Rich Text Editor does not involve learning how to develop for a Payload rich text editor. Instead, you can invest your time and effort into learning Slate, an open-source tool that will allow you to apply your learnings elsewhere as well. ### Config -| Option | Description | -| ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------- | -| **`name`** \* | To be used as the property name when stored and retrieved from the database. | -| **`label`** | Used as a field label in the Admin panel and to name the generated GraphQL type. | -| **`validate`** | Provide a custom validation function that will be executed on both the Admin panel and the backend. [More](/docs/fields/overview#validation) | -| **`saveToJWT`** | If this field is top-level and nested in a config supporting [Authentication](/docs/authentication/config), include its data in the user JWT. | -| **`hooks`** | Provide field-based hooks to control logic for this field. [More](/docs/fields/overview#field-level-hooks) | -| **`access`** | Provide field-based access control to denote what users can see and do with this field's data. [More](/docs/fields/overview#field-level-access-control) | -| **`hidden`** | Restrict this field's visibility from all APIs entirely. Will still be saved to the database, but will not appear in any API or the Admin panel. | -| **`defaultValue`** | Provide data to be used for this field's default value. | -| **`localized`** | Enable localization for this field. Requires [localization to be enabled](/docs/configuration/localization) in the Base config. | -| **`required`** | Require this field to have a value. | -| **`admin`** | Admin-specific configuration. See below for [more detail](#admin-config). | +| Option | Description | +| ---------------- | ----------- | +| **`name`** * | To be used as the property name when stored and retrieved from the database. | +| **`label`** | Used as a field label in the Admin panel and to name the generated GraphQL type. | +| **`validate`** | Provide a custom validation function that will be executed on both the Admin panel and the backend. [More](/docs/fields/overview#validation) | +| **`saveToJWT`** | If this field is top-level and nested in a config supporting [Authentication](/docs/authentication/config), include its data in the user JWT. | +| **`hooks`** | Provide field-based hooks to control logic for this field. [More](/docs/fields/overview#field-level-hooks) | +| **`access`** | Provide field-based access control to denote what users can see and do with this field's data. [More](/docs/fields/overview#field-level-access-control) | +| **`hidden`** | Restrict this field's visibility from all APIs entirely. Will still be saved to the database, but will not appear in any API or the Admin panel. | +| **`defaultValue`** | Provide data to be used for this field's default value. | +| **`localized`** | Enable localization for this field. Requires [localization to be enabled](/docs/configuration/localization) in the Base config. | +| **`required`** | Require this field to have a value. | +| **`admin`** | Admin-specific configuration. See below for [more detail](#admin-config). | -_\* An asterisk denotes that a property is required._ +*\* An asterisk denotes that a property is required.* ### Admin config @@ -85,11 +76,8 @@ The default `leaves` available in Payload are: The built-in `relationship` element is a powerful way to reference other Documents directly within your Rich Text editor. - Tip: -
- To enable collections to be selected within the Rich Text relationship, you - need to enable the collection admin option of{" "} - enableRichTextRelationship. + Tip:
+ To enable collections to be selected within the Rich Text relationship, you need to enable the collection admin option of enableRichTextRelationship.
### Specifying which elements and leaves to allow @@ -104,11 +92,11 @@ Once you're up to speed with the general concepts involved, you can pass in your **Both custom elements and leaves are defined via the following config:** -| Property | Description | -| --------------- | ---------------------------------------------------------- | -| **`name`** \* | The name to be used as a `type` for this element. | -| **`Button`** \* | A React component to be rendered in the Rich Text toolbar. | -| **`plugins`** | An array of plugins to provide to the Rich Text editor. | +| Property | Description | +| ---------------- | ----------- | +| **`name`** * | The name to be used as a `type` for this element. | +| **`Button`** * | A React component to be rendered in the Rich Text toolbar. | +| **`plugins`** | An array of plugins to provide to the Rich Text editor. | Custom `Element`s also require the `Element` property set to a Reactt component to be rendered as the `Element` within the rich text editor itself. @@ -117,7 +105,6 @@ Custom `Leaf` objects follow a similar pattern but require you to define the `Le ### Example `collections/ExampleCollection.js` - ```js { slug: 'example-collection', @@ -169,68 +156,110 @@ For more examples regarding how to define your own elements and leaves, check ou As the Rich Text field saves its content in a JSON format, you'll need to render it as HTML yourself. Here is an example for how to generate JSX / HTML from Rich Text content: ```js -import React, { Fragment } from "react"; -import escapeHTML from "escape-html"; -import { Text } from "slate"; +import React, { Fragment } from 'react'; +import escapeHTML from 'escape-html'; +import { Text } from 'slate'; -const serialize = (children) => - children.map((node, i) => { - if (Text.isText(node)) { - let text = ( - +const serialize = (children) => children.map((node, i) => { + if (Text.isText(node)) { + let text = ; + + if (node.bold) { + text = ( + + {text} + + ); + } + + if (node.code) { + text = ( + + {text} + + ); + } + + if (node.italic) { + text = ( + + {text} + + ); + } + + // Handle other leaf types here... + + return ( + + {text} + + ); + } + + if (!node) { + return null; + } + + switch (node.type) { + case 'h1': + return ( +

+ {serialize(node.children)} +

+ ); + // Iterate through all headings here... + case 'h6': + return ( +
+ {serialize(node.children)} +
+ ); + case 'quote': + return ( +
+ {serialize(node.children)} +
+ ); + case 'ul': + return ( +
    + {serialize(node.children)} +
+ ); + case 'ol': + return ( +
    + {serialize(node.children)} +
+ ); + case 'li': + return ( +
  • + {serialize(node.children)} +
  • + ); + case 'link': + return ( + + {serialize(node.children)} + ); - if (node.bold) { - text = {text}; - } - - if (node.code) { - text = {text}; - } - - if (node.italic) { - text = {text}; - } - - // Handle other leaf types here... - - return {text}; - } - - if (!node) { - return null; - } - - switch (node.type) { - case "h1": - return

    {serialize(node.children)}

    ; - // Iterate through all headings here... - case "h6": - return
    {serialize(node.children)}
    ; - case "quote": - return
    {serialize(node.children)}
    ; - case "ul": - return
      {serialize(node.children)}
    ; - case "ol": - return
      {serialize(node.children)}
    ; - case "li": - return
  • {serialize(node.children)}
  • ; - case "link": - return ( - - {serialize(node.children)} - - ); - - default: - return

    {serialize(node.children)}

    ; - } - }); + default: + return ( +

    + {serialize(node.children)} +

    + ); + } +}); ``` - Note: -
    - The above example is for how to render to JSX, although for plain HTML the - pattern is similar. Just remove the JSX and return HTML strings instead! + Note:
    + The above example is for how to render to JSX, although for plain HTML the pattern is similar. Just remove the JSX and return HTML strings instead!
    diff --git a/docs/fields/row.mdx b/docs/fields/row.mdx index c65619a497..32ad232bbe 100644 --- a/docs/fields/row.mdx +++ b/docs/fields/row.mdx @@ -6,24 +6,22 @@ desc: With the Row field you can arrange fields next to each other in the Admin keywords: row, fields, config, configuration, documentation, Content Management System, cms, headless, javascript, node, react, express --- - - The Row field is presentational-only and only affects the Admin panel. By - using it, you can arrange fields next to each other horizontally. + + The Row field is presentational-only and only affects the Admin panel. By using it, you can arrange fields next to each other horizontally. ### Config -| Option | Description | -| --------------- | ------------------------------------------------------------------------------------------------------------------------ | -| **`fields`** \* | Array of field types to nest within this Row. | -| **`admin`** | Admin-specific configuration. See the [default field admin config](/docs/fields/overview#admin-config) for more details. | +| Option | Description | +| ---------------- | ----------- | +| **`fields`** * | Array of field types to nest within this Row. | +| **`admin`** | Admin-specific configuration. See the [default field admin config](/docs/fields/overview#admin-config) for more details. | -_\* An asterisk denotes that a property is required._ +*\* An asterisk denotes that a property is required.* ### Example `collections/ExampleCollection.js` - ```js { slug: 'example-collection', diff --git a/docs/fields/select.mdx b/docs/fields/select.mdx index 204fb857b3..08577ac24e 100644 --- a/docs/fields/select.mdx +++ b/docs/fields/select.mdx @@ -6,47 +6,40 @@ desc: The Select field provides a dropdown-style interface for choosing options keywords: select, multi-select, fields, config, configuration, documentation, Content Management System, cms, headless, javascript, node, react, express --- - - The Select field provides a dropdown-style interface for choosing options from - a predefined list as an enumeration. + + The Select field provides a dropdown-style interface for choosing options from a predefined list as an enumeration. ### Config -| Option | Description | -| ------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| **`name`** \* | To be used as the property name when stored and retrieved from the database. | -| **`options`** \* | Array of options to allow the field to store. Can either be an array of strings, or an array of objects containing an `option` string and a `value` string. | -| **`hasMany`** | Boolean when, if set to `true`, allows this field to have many selections instead of only one. | -| **`label`** | Used as a field label in the Admin panel and to name the generated GraphQL type. | -| **`unique`** | Enforce that each entry in the Collection has a unique value for this field. | -| **`validate`** | Provide a custom validation function that will be executed on both the Admin panel and the backend. [More](/docs/fields/overview#validation) | -| **`index`** | Build a [MongoDB index](https://docs.mongodb.com/manual/indexes/) for this field to produce faster queries. Set this field to `true` if your users will perform queries on this field's data often. | -| **`saveToJWT`** | If this field is top-level and nested in a config supporting [Authentication](/docs/authentication/config), include its data in the user JWT. | -| **`hooks`** | Provide field-based hooks to control logic for this field. [More](/docs/fields/overview#field-level-hooks) | -| **`access`** | Provide field-based access control to denote what users can see and do with this field's data. [More](/docs/fields/overview#field-level-access-control) | -| **`hidden`** | Restrict this field's visibility from all APIs entirely. Will still be saved to the database, but will not appear in any API or the Admin panel. | -| **`defaultValue`** | Provide data to be used for this field's default value. | -| **`localized`** | Enable localization for this field. Requires [localization to be enabled](/docs/configuration/localization) in the Base config. | -| **`required`** | Require this field to have a value. | -| **`admin`** | Admin-specific configuration. See the [default field admin config](/docs/fields/overview#admin-config) for more details. | +| Option | Description | +| ---------------- | ----------- | +| **`name`** * | To be used as the property name when stored and retrieved from the database. | +| **`options`** * | Array of options to allow the field to store. Can either be an array of strings, or an array of objects containing an `option` string and a `value` string. | +| **`hasMany`** | Boolean when, if set to `true`, allows this field to have many selections instead of only one. | +| **`label`** | Used as a field label in the Admin panel and to name the generated GraphQL type. | +| **`unique`** | Enforce that each entry in the Collection has a unique value for this field. | +| **`validate`** | Provide a custom validation function that will be executed on both the Admin panel and the backend. [More](/docs/fields/overview#validation) | +| **`index`** | Build a [MongoDB index](https://docs.mongodb.com/manual/indexes/) for this field to produce faster queries. Set this field to `true` if your users will perform queries on this field's data often. | +| **`saveToJWT`** | If this field is top-level and nested in a config supporting [Authentication](/docs/authentication/config), include its data in the user JWT. | +| **`hooks`** | Provide field-based hooks to control logic for this field. [More](/docs/fields/overview#field-level-hooks) | +| **`access`** | Provide field-based access control to denote what users can see and do with this field's data. [More](/docs/fields/overview#field-level-access-control) | +| **`hidden`** | Restrict this field's visibility from all APIs entirely. Will still be saved to the database, but will not appear in any API or the Admin panel. | +| **`defaultValue`** | Provide data to be used for this field's default value. | +| **`localized`** | Enable localization for this field. Requires [localization to be enabled](/docs/configuration/localization) in the Base config. | +| **`required`** | Require this field to have a value. | +| **`admin`** | Admin-specific configuration. See the [default field admin config](/docs/fields/overview#admin-config) for more details. | -_\* An asterisk denotes that a property is required._ +*\* An asterisk denotes that a property is required.* - Important: -
    - Option values should be strings that do not contain hyphens or special - characters due to GraphQL enumeration naming constraints. Underscores are - allowed. If you determine you need your option values to be non-strings or - contain special characters, they will be formatted accordingly before being - used as a GraphQL enum. + Important:
    + Option values should be strings that do not contain hyphens or special characters due to GraphQL enumeration naming constraints. Underscores are allowed. If you determine you need your option values to be non-strings or contain special characters, they will be formatted accordingly before being used as a GraphQL enum.
    ### Example `collections/ExampleCollection.js` - ```js { slug: 'example-collection', diff --git a/docs/fields/text.mdx b/docs/fields/text.mdx index 6ee05dc5a1..e7b14e7f5b 100644 --- a/docs/fields/text.mdx +++ b/docs/fields/text.mdx @@ -6,32 +6,31 @@ desc: Text field types simply save a string to the database and provide the Admi keywords: text, fields, config, configuration, documentation, Content Management System, cms, headless, javascript, node, react, express --- - - The Text field type is one of the most commonly used fields. It saves a string - to the database and provides the Admin panel with a simple text input. + + The Text field type is one of the most commonly used fields. It saves a string to the database and provides the Admin panel with a simple text input. ### Config -| Option | Description | -| ------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| **`name`** \* | To be used as the property name when stored and retrieved from the database. | -| **`label`** | Used as a field label in the Admin panel and to name the generated GraphQL type. | -| **`unique`** | Enforce that each entry in the Collection has a unique value for this field. | -| **`minLength`** | Used by the default validation function to ensure values are of a minimum character length. | -| **`maxLength`** | Used by the default validation function to ensure values are of a maximum character length. | -| **`validate`** | Provide a custom validation function that will be executed on both the Admin panel and the backend. [More](/docs/fields/overview#validation) | -| **`index`** | Build a [MongoDB index](https://docs.mongodb.com/manual/indexes/) for this field to produce faster queries. Set this field to `true` if your users will perform queries on this field's data often. | -| **`saveToJWT`** | If this field is top-level and nested in a config supporting [Authentication](/docs/authentication/config), include its data in the user JWT. | -| **`hooks`** | Provide field-based hooks to control logic for this field. [More](/docs/fields/overview#field-level-hooks) | -| **`access`** | Provide field-based access control to denote what users can see and do with this field's data. [More](/docs/fields/overview#field-level-access-control) | -| **`hidden`** | Restrict this field's visibility from all APIs entirely. Will still be saved to the database, but will not appear in any API or the Admin panel. | -| **`defaultValue`** | Provide data to be used for this field's default value. | -| **`localized`** | Enable localization for this field. Requires [localization to be enabled](/docs/configuration/localization) in the Base config. | -| **`required`** | Require this field to have a value. | -| **`admin`** | Admin-specific configuration. See below for [more detail](#admin). | +| Option | Description | +| ---------------- | ----------- | +| **`name`** * | To be used as the property name when stored and retrieved from the database. | +| **`label`** | Used as a field label in the Admin panel and to name the generated GraphQL type. | +| **`unique`** | Enforce that each entry in the Collection has a unique value for this field. | +| **`minLength`** | Used by the default validation function to ensure values are of a minimum character length. | +| **`maxLength`** | Used by the default validation function to ensure values are of a maximum character length. | +| **`validate`** | Provide a custom validation function that will be executed on both the Admin panel and the backend. [More](/docs/fields/overview#validation) | +| **`index`** | Build a [MongoDB index](https://docs.mongodb.com/manual/indexes/) for this field to produce faster queries. Set this field to `true` if your users will perform queries on this field's data often. | +| **`saveToJWT`** | If this field is top-level and nested in a config supporting [Authentication](/docs/authentication/config), include its data in the user JWT. | +| **`hooks`** | Provide field-based hooks to control logic for this field. [More](/docs/fields/overview#field-level-hooks) | +| **`access`** | Provide field-based access control to denote what users can see and do with this field's data. [More](/docs/fields/overview#field-level-access-control) | +| **`hidden`** | Restrict this field's visibility from all APIs entirely. Will still be saved to the database, but will not appear in any API or the Admin panel. | +| **`defaultValue`** | Provide data to be used for this field's default value. | +| **`localized`** | Enable localization for this field. Requires [localization to be enabled](/docs/configuration/localization) in the Base config. | +| **`required`** | Require this field to have a value. | +| **`admin`** | Admin-specific configuration. See below for [more detail](#admin). | -_\* An asterisk denotes that a property is required._ +*\* An asterisk denotes that a property is required.* ### Admin config @@ -48,7 +47,6 @@ Set this property to a string that will be used for browser autocomplete. ### Example `collections/ExampleCollection.js` - ```js { slug: 'example-collection', diff --git a/docs/fields/textarea.mdx b/docs/fields/textarea.mdx index d1153d42af..891a0c2959 100644 --- a/docs/fields/textarea.mdx +++ b/docs/fields/textarea.mdx @@ -6,32 +6,31 @@ desc: Textarea field types save a string to the database, similar to the Text fi keywords: textarea, fields, config, configuration, documentation, Content Management System, cms, headless, javascript, node, react, express --- - - The Textarea field is almost identical to the Text field but it features a - slightly larger input that is better suited to edit longer text. + + The Textarea field is almost identical to the Text field but it features a slightly larger input that is better suited to edit longer text. ### Config -| Option | Description | -| ------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| **`name`** \* | To be used as the property name when stored and retrieved from the database. | -| **`label`** | Used as a field label in the Admin panel and to name the generated GraphQL type. | -| **`unique`** | Enforce that each entry in the Collection has a unique value for this field. | -| **`minLength`** | Used by the default validation function to ensure values are of a minimum character length. | -| **`maxLength`** | Used by the default validation function to ensure values are of a maximum character length. | -| **`validate`** | Provide a custom validation function that will be executed on both the Admin panel and the backend. [More](/docs/fields/overview#validation) | -| **`index`** | Build a [MongoDB index](https://docs.mongodb.com/manual/indexes/) for this field to produce faster queries. Set this field to `true` if your users will perform queries on this field's data often. | -| **`saveToJWT`** | If this field is top-level and nested in a config supporting [Authentication](/docs/authentication/config), include its data in the user JWT. | -| **`hooks`** | Provide field-based hooks to control logic for this field. [More](/docs/fields/overview#field-level-hooks) | -| **`access`** | Provide field-based access control to denote what users can see and do with this field's data. [More](/docs/fields/overview#field-level-access-control) | -| **`hidden`** | Restrict this field's visibility from all APIs entirely. Will still be saved to the database, but will not appear in any API or the Admin panel. | -| **`defaultValue`** | Provide data to be used for this field's default value. | -| **`localized`** | Enable localization for this field. Requires [localization to be enabled](/docs/configuration/localization) in the Base config. | -| **`required`** | Require this field to have a value. | -| **`admin`** | Admin-specific configuration. See below for [more detail](#admin). | +| Option | Description | +| ---------------- | ----------- | +| **`name`** * | To be used as the property name when stored and retrieved from the database. | +| **`label`** | Used as a field label in the Admin panel and to name the generated GraphQL type. | +| **`unique`** | Enforce that each entry in the Collection has a unique value for this field. | +| **`minLength`** | Used by the default validation function to ensure values are of a minimum character length. | +| **`maxLength`** | Used by the default validation function to ensure values are of a maximum character length. | +| **`validate`** | Provide a custom validation function that will be executed on both the Admin panel and the backend. [More](/docs/fields/overview#validation) | +| **`index`** | Build a [MongoDB index](https://docs.mongodb.com/manual/indexes/) for this field to produce faster queries. Set this field to `true` if your users will perform queries on this field's data often. | +| **`saveToJWT`** | If this field is top-level and nested in a config supporting [Authentication](/docs/authentication/config), include its data in the user JWT. | +| **`hooks`** | Provide field-based hooks to control logic for this field. [More](/docs/fields/overview#field-level-hooks) | +| **`access`** | Provide field-based access control to denote what users can see and do with this field's data. [More](/docs/fields/overview#field-level-access-control) | +| **`hidden`** | Restrict this field's visibility from all APIs entirely. Will still be saved to the database, but will not appear in any API or the Admin panel. | +| **`defaultValue`** | Provide data to be used for this field's default value. | +| **`localized`** | Enable localization for this field. Requires [localization to be enabled](/docs/configuration/localization) in the Base config. | +| **`required`** | Require this field to have a value. | +| **`admin`** | Admin-specific configuration. See below for [more detail](#admin). | -_\* An asterisk denotes that a property is required._ +*\* An asterisk denotes that a property is required.* ### Admin config @@ -48,7 +47,6 @@ Set this property to a string that will be used for browser autocomplete. ### Example `collections/ExampleCollection.js` - ```js { slug: 'example-collection', diff --git a/docs/fields/upload.mdx b/docs/fields/upload.mdx index e05d8f6a85..cc553fc305 100644 --- a/docs/fields/upload.mdx +++ b/docs/fields/upload.mdx @@ -6,18 +6,13 @@ desc: Upload fields will allow a file to be uploaded, only from a collection sup keywords: upload, images media, fields, config, configuration, documentation, Content Management System, cms, headless, javascript, node, react, express --- - - The Upload field allows for the selection of a Document from a collection - supporting Uploads, and formats the selection as a thumbnail in the Admin - panel. + + The Upload field allows for the selection of a Document from a collection supporting Uploads, and formats the selection as a thumbnail in the Admin panel. - Important: -
    - To use this field, you need to have a Collection configured to allow Uploads. - For more information, click here to read - about how to enable Uploads on a collection by collection basis. + Important:
    + To use this field, you need to have a Collection configured to allow Uploads. For more information, click here to read about how to enable Uploads on a collection by collection basis.
    **Example uses:** @@ -28,30 +23,29 @@ keywords: upload, images media, fields, config, configuration, documentation, Co ### Config -| Option | Description | -| -------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| **`name`** \* | To be used as the property name when stored and retrieved from the database. | -| **`*relationTo`** \* | Provide a single collection `slug` to allow this field to accept a relation to. Note: the related collection must be configured to support Uploads. | -| **`hasMany`** | Boolean when, if set to `true`, allows this field to have many relations instead of only one. | -| **`label`** | Used as a field label in the Admin panel and to name the generated GraphQL type. | -| **`unique`** | Enforce that each entry in the Collection has a unique value for this field. | -| **`validate`** | Provide a custom validation function that will be executed on both the Admin panel and the backend. [More](/docs/fields/overview#validation) | +| Option | Description | +| ---------------- | ----------- | +| **`name`** * | To be used as the property name when stored and retrieved from the database. | +| **`*relationTo`** * | Provide a single collection `slug` to allow this field to accept a relation to. Note: the related collection must be configured to support Uploads. | +| **`hasMany`** | Boolean when, if set to `true`, allows this field to have many relations instead of only one. | +| **`label`** | Used as a field label in the Admin panel and to name the generated GraphQL type. | +| **`unique`** | Enforce that each entry in the Collection has a unique value for this field. | +| **`validate`** | Provide a custom validation function that will be executed on both the Admin panel and the backend. [More](/docs/fields/overview#validation) | | **`index`** | Build a [MongoDB index](https://docs.mongodb.com/manual/indexes/) for this field to produce faster queries. Set this field to `true` if your users will perform queries on this field's data often. | -| **`saveToJWT`** | If this field is top-level and nested in a config supporting [Authentication](/docs/authentication/config), include its data in the user JWT. | -| **`hooks`** | Provide field-based hooks to control logic for this field. [More](/docs/fields/overview#field-level-hooks) | -| **`access`** | Provide field-based access control to denote what users can see and do with this field's data. [More](/docs/fields/overview#field-level-access-control) | -| **`hidden`** | Restrict this field's visibility from all APIs entirely. Will still be saved to the database, but will not appear in any API or the Admin panel. | -| **`defaultValue`** | Provide data to be used for this field's default value. | -| **`localized`** | Enable localization for this field. Requires [localization to be enabled](/docs/configuration/localization) in the Base config. | -| **`required`** | Require this field to have a value. | -| **`admin`** | Admin-specific configuration. See the [default field admin config](/docs/fields/overview#admin-config) for more details. | +| **`saveToJWT`** | If this field is top-level and nested in a config supporting [Authentication](/docs/authentication/config), include its data in the user JWT. | +| **`hooks`** | Provide field-based hooks to control logic for this field. [More](/docs/fields/overview#field-level-hooks) | +| **`access`** | Provide field-based access control to denote what users can see and do with this field's data. [More](/docs/fields/overview#field-level-access-control) | +| **`hidden`** | Restrict this field's visibility from all APIs entirely. Will still be saved to the database, but will not appear in any API or the Admin panel. | +| **`defaultValue`** | Provide data to be used for this field's default value. | +| **`localized`** | Enable localization for this field. Requires [localization to be enabled](/docs/configuration/localization) in the Base config. | +| **`required`** | Require this field to have a value. | +| **`admin`** | Admin-specific configuration. See the [default field admin config](/docs/fields/overview#admin-config) for more details. | -_\* An asterisk denotes that a property is required._ +*\* An asterisk denotes that a property is required.* ### Example `collections/ExampleCollection.js` - ```js { slug: 'example-collection', diff --git a/docs/getting-started/concepts.mdx b/docs/getting-started/concepts.mdx index 5bce155c5d..bf04d88816 100644 --- a/docs/getting-started/concepts.mdx +++ b/docs/getting-started/concepts.mdx @@ -11,7 +11,7 @@ Payload is based around a small and intuitive set of concepts. Before starting t ### Config - The Payload config is where you configure everything that Payload does. + The Payload config is where you configure everything that Payload does. By default, the Payload config lives in the root folder of your code and is named `payload.config.js` (`payload.config.ts` if you're using TypeScript), but you can customize its name and where you store it. You can write full functions and even full React components right into your config. @@ -19,8 +19,7 @@ By default, the Payload config lives in the root folder of your code and is name ### Collections - A Collection represents a type of content that Payload will store and can - contain many documents. + A Collection represents a type of content that Payload will store and can contain many documents. Collections define the shape of your data as well as all functionalities attached to that data. They will contain or many "documents", all corresponding with the same fields and functionalities that you define. @@ -30,8 +29,7 @@ They can represent anything you can store in a database - for example - pages, p ### Globals - A Global is a "one-off" piece of content that is perfect for storing - navigational structures, themes, top-level meta data, and more. + A Global is a "one-off" piece of content that is perfect for storing navigational structures, themes, top-level meta data, and more. Globals are in many ways similar to Collections, but there is only ever **one** instance of a Global, whereas Collections can contain many documents. @@ -39,8 +37,7 @@ Globals are in many ways similar to Collections, but there is only ever **one** ### Fields - Fields are the building blocks of Payload. Collections and Globals both use - Fields to define the shape of the data that they store. + Fields are the building blocks of Payload. Collections and Globals both use Fields to define the shape of the data that they store. Payload comes with [many different field types](../fields/overview) that give you a ton of flexibility while designing your API. Each Field type has its own potential properties that allow you to customize how they work. @@ -48,8 +45,7 @@ Payload comes with [many different field types](../fields/overview) that give yo ### Hooks - Hooks are where you can "tie in" to existing Payload actions to perform your - own additional logic or modify how Payload operates altogether. + Hooks are where you can "tie in" to existing Payload actions to perform your own additional logic or modify how Payload operates altogether. Hooks are an extremely powerful concept and are central to extending and customizing your app. Payload provides a wide variety of hooks which you can utilize. For example, imagine if you'd like to send an email every time a document is created in your Orders collection. To do so, you can add an `afterChange` hook function to your Orders collection that receives the Order data and allows you to send an email accordingly. @@ -59,8 +55,7 @@ There are many more potential reasons to use Hooks. For more, visit the [Hooks d ### Access Control - Access Control refers to Payload's system of defining who can do what to your - API. + Access Control refers to Payload's system of defining who can do what to your API. Access Control is extremely powerful but easy and intuitive to manage. You can easily define your own full-blown RBAC (role-based access control) or any other access control pattern that your scenario requires. No conventions or structure is forced on you whatsoever. @@ -70,11 +65,10 @@ For more, visit the [Access Control documentation](/docs/access-control/overview ### Depth - "Depth" gives you control over how many levels down related documents should - be automatically populated when retrieved. + "Depth" gives you control over how many levels down related documents should be automatically populated when retrieved. -You can specify population `depth` via query parameter in the REST API and by an option in the local API. _Depth has no effect in the GraphQL API, because there, depth is based on the shape of your queries._ +You can specify population `depth` via query parameter in the REST API and by an option in the local API. *Depth has no effect in the GraphQL API, because there, depth is based on the shape of your queries.* **For example, let's look the following Collections:** `departments`, `users`, `posts` diff --git a/docs/getting-started/installation.mdx b/docs/getting-started/installation.mdx index 097e7fe6bf..450792ee79 100644 --- a/docs/getting-started/installation.mdx +++ b/docs/getting-started/installation.mdx @@ -2,7 +2,7 @@ title: Installation label: Installation order: 30 -desc: How do I install Payload CMS? To quickly get started with Payload, simply run npx create-payload-app. Read more for further instructions or to install from scratch. +desc: To quickly get started with Payload, simply run npx create-payload-app or install from scratch. keywords: documentation, getting started, guide, Content Management System, cms, headless, javascript, node, react, express --- diff --git a/docs/getting-started/what-is-payload.mdx b/docs/getting-started/what-is-payload.mdx index 843f2c1578..bf7aa59785 100644 --- a/docs/getting-started/what-is-payload.mdx +++ b/docs/getting-started/what-is-payload.mdx @@ -2,7 +2,7 @@ title: What is Payload? label: What is Payload? order: 10 -desc: What is Payload? Payload is a next-gen headless CMS and application framework, equipped with dozens of features to provide a massive boost to your development process. +desc: Payload is a next-gen headless Content Management System (CMS) and application framework. keywords: documentation, getting started, guide, Content Management System, cms, headless, javascript, node, react, express --- diff --git a/docs/graphql/extending.mdx b/docs/graphql/extending.mdx index ce91308c85..d7cb2dcef7 100644 --- a/docs/graphql/extending.mdx +++ b/docs/graphql/extending.mdx @@ -10,10 +10,10 @@ You can add your own GraphQL queries and mutations to Payload, making use of all To do so, add your queries and mutations to the main Payload config as follows: -| Config Path | Description | -| ------------------- | --------------------------------------------------------------------------- | -| `graphQL.queries` | Function that returns an object containing keys to custom GraphQL queries | -| `graphQL.mutations` | Function that returns an object containing keys to custom GraphQL mutations | +| Config Path | Description | +| -------------------- | -------------| +| `graphQL.queries` | Function that returns an object containing keys to custom GraphQL queries | +| `graphQL.mutations` | Function that returns an object containing keys to custom GraphQL mutations | The above properties each receive a function that is defined with the following arguments: @@ -34,18 +34,18 @@ Both `graphQL.queries` and `graphQL.mutations` functions should return an object `payload.config.js`: ```js -import { buildConfig } from "payload/config"; -import myCustomQueryResolver from "./graphQL/resolvers/myCustomQueryResolver"; +import { buildConfig } from 'payload/config'; +import myCustomQueryResolver from './graphQL/resolvers/myCustomQueryResolver'; export default buildConfig({ - serverURL: "http://localhost:3000", + serverURL: 'http://localhost:3000', graphQL: { // highlight-start queries: (GraphQL, payload) => { return { MyCustomQuery: { type: new GraphQL.GraphQLObjectType({ - name: "MyCustomQuery", + name: 'MyCustomQuery', fields: { text: { type: GraphQL.GraphQLString, @@ -57,14 +57,14 @@ export default buildConfig({ args: { argNameHere: { type: new GraphQL.GraphQLNonNull(GraphQLString), - }, + } }, resolve: myCustomQueryResolver, - }), - }, - }; - }, + }) + } + } + } // highlight-end - }, -}); + } +}) ``` diff --git a/docs/hooks/collections.mdx b/docs/hooks/collections.mdx index 1c96ba2171..488fc7b848 100644 --- a/docs/hooks/collections.mdx +++ b/docs/hooks/collections.mdx @@ -27,7 +27,6 @@ Additionally, `auth`-enabled collections feature the following hooks: All collection Hook properties accept arrays of synchronous or asynchronous functions. Each Hook type receives specific arguments and has the ability to modify specific outputs. `collections/example-hooks.js` - ```js // Collection config module.exports = { @@ -64,7 +63,7 @@ const beforeOperationHook = async ({ operation, // name of the operation }) => { return args; // Return operation arguments as necessary -}; +} ``` ### beforeValidate @@ -79,7 +78,7 @@ const beforeValidateHook = async ({ originalDoc, // original document }) => { return data; // Return data to either create or update a document with -}; +} ``` ### beforeChange @@ -94,7 +93,7 @@ const beforeChangeHook = async ({ originalDoc, // original document }) => { return data; // Return data to either create or update a document with -}; +} ``` ### afterChange @@ -108,7 +107,7 @@ const afterChangeHook = async ({ operation, // name of the operation ie. 'create', 'update' }) => { return data; -}; +} ``` ### beforeRead @@ -122,7 +121,7 @@ const beforeReadHook = async ({ query, // JSON formatted query }) => { return doc; -}; +} ``` ### afterRead @@ -136,7 +135,7 @@ const afterReadHook = async ({ query, // JSON formatted query }) => { return doc; -}; +} ``` ### beforeDelete @@ -173,7 +172,7 @@ const afterLoginHook = async ({ token, // user token }) => { return user; -}; +} ``` ### afterForgotPassword @@ -187,5 +186,5 @@ const afterLoginHook = async ({ token, // user token }) => { return user; -}; +} ``` diff --git a/docs/hooks/fields.mdx b/docs/hooks/fields.mdx index e82d75dc5c..777922733a 100644 --- a/docs/hooks/fields.mdx +++ b/docs/hooks/fields.mdx @@ -26,7 +26,6 @@ Field-level hooks offer incredible potential for encapsulating your logic. They ## Config Example field configuration: - ```js { name: 'name', @@ -48,33 +47,27 @@ Example field configuration: All field-level hooks are formatted to accept the same arguments, although some arguments may be `undefined` based on which field hook you are utilizing. - Tip: -
    - It's a good idea to conditionally scope your logic based on which operation is - executing. + Tip:
    + It's a good idea to conditionally scope your logic based on which operation is executing.
    #### Arguments Field Hooks receive one `args` argument that contains the following properties: -| Option | Description | -| ----------------- | ------------------------------------------------------------------------------------------------ | +| Option | Description | +| ----------------- | -------------| | **`value`** | The value of the field, before any updating. Will return `undefined` within `create` operations. | -| **`data`** | The data passed to update the field with in `create` and `update` operations. | -| **`originalDoc`** | The full original document in `update` or `read` operations. | -| **`operation`** | A string relating to which operation the field type is currently executing within. | -| **`req`** | The Express `request` object. It is mocked for Local API operations. | +| **`data`** | The data passed to update the field with in `create` and `update` operations. | +| **`originalDoc`** | The full original document in `update` or `read` operations. | +| **`operation`** | A string relating to which operation the field type is currently executing within. | +| **`req`** | The Express `request` object. It is mocked for Local API operations. | #### Return value Field hooks **must** return the intended value for the field to be used in the operation. You can modify the return value of the field before the operation continues, or simply send the `value` that you receive through the hook's argument. If you return `undefined` within a `beforeChange` or `beforeValidate` hook, the property will be unset from its document. - Important -
    - Due to GraphQL's typed nature, you should never change the type of data that - you return from a field, otherwise GraphQL will produce errors. If you need to - change the shape or type of data, reconsider Field Hooks and instead evaluate - if Collection / Global hooks might suit you better. + Important
    + Due to GraphQL's typed nature, you should never change the type of data that you return from a field, otherwise GraphQL will produce errors. If you need to change the shape or type of data, reconsider Field Hooks and instead evaluate if Collection / Global hooks might suit you better.
    diff --git a/docs/hooks/globals.mdx b/docs/hooks/globals.mdx index c5ce4e1bba..b89f33d1fa 100644 --- a/docs/hooks/globals.mdx +++ b/docs/hooks/globals.mdx @@ -19,7 +19,6 @@ Globals feature the ability to define the following hooks: All Global Hook properties accept arrays of synchronous or asynchronous functions. Each Hook type receives specific arguments and has the ability to modify specific outputs. `globals/example-hooks.js` - ```js // Global config module.exports = { @@ -49,7 +48,7 @@ const beforeValidateHook = async ({ originalDoc, // original document }) => { return data; // Return data to either create or update a document with -}; +} ``` ### beforeChange @@ -64,7 +63,7 @@ const beforeChangeHook = async ({ originalDoc, // original document }) => { return data; // Return data to either create or update a document with -}; +} ``` ### afterChange @@ -78,7 +77,7 @@ const afterChangeHook = async ({ operation, // name of the operation ie. 'create', 'update' }) => { return data; -}; +} ``` ### beforeRead diff --git a/docs/hooks/overview.mdx b/docs/hooks/overview.mdx index 4ec4716e83..1e040d121a 100644 --- a/docs/hooks/overview.mdx +++ b/docs/hooks/overview.mdx @@ -7,9 +7,7 @@ keywords: hooks, overview, config, configuration, documentation, Content Managem --- - Hooks are powerful ways to tie into existing Payload actions in order to add - your own logic like integrating with third-party APIs, adding auto-generated - data, or modifing Payload's base functionality. + Hooks are powerful ways to tie into existing Payload actions in order to add your own logic like integrating with third-party APIs, adding auto-generated data, or modifing Payload's base functionality. **With Hooks, you can transform Payload from a traditional CMS into a fully-fledged application framework.** diff --git a/docs/local-api/overview.mdx b/docs/local-api/overview.mdx index 082ab681d9..8c7ecd692f 100644 --- a/docs/local-api/overview.mdx +++ b/docs/local-api/overview.mdx @@ -9,14 +9,8 @@ keywords: local api, config, configuration, documentation, Content Management Sy The Payload Local API gives you the ability to execute the same operations that are available through REST and GraphQL within Node, directly on your server. Here, you don't need to deal with server latency or network speed whatsoever and can interact directly with your database. - Tip: -
    - The Local API is incredibly powerful when used with server-side rendering app - frameworks like NextJS. With other headless CMS, you need to request your data - from third-party servers which can add significant loading time to your - server-rendered pages. With Payload, you don't have to leave your server to - gather the data you need. It can be incredibly fast and is definitely a game - changer. + Tip:
    + The Local API is incredibly powerful when used with server-side rendering app frameworks like NextJS. With other headless CMS, you need to request your data from third-party servers which can add significant loading time to your server-rendered pages. With Payload, you don't have to leave your server to gather the data you need. It can be incredibly fast and is definitely a game changer.
    Here are some common examples of how you can use the Local API: @@ -34,15 +28,14 @@ You can gain access to the currently running `payload` object via two ways: You can import or require `payload` into your own files after it's been initialized, but you need to make sure that your `import` / `require` statements come **after** you call `payload.init()`—otherwise Payload won't have been initialized yet. That might be obvious. To us, it's usually not. Example: - ```js -import payload from "payload"; +import payload from 'payload'; const afterChangeHook = async () => { const posts = await payload.find({ - collection: "posts", + collection: 'posts', }); -}; +} ``` ##### Accessing from the `req` @@ -50,38 +43,34 @@ const afterChangeHook = async () => { Payload is available anywhere you have access to the Express `req` - including within your access control and hook functions. Example: - ```js -const afterChangeHook = async ({ req: { payload } }) => { +const afterChangeHook = async ({ req: { payload }}) => { const posts = await payload.find({ - collection: "posts", + collection: 'posts', }); -}; +} ``` ### Local options available You can specify more options within the Local API vs. REST or GraphQL due to the server-only context that they are executed in. -| Local Option | Description | -| ------------------ | -------------------------------------------------------------------------------------------------------------------- | -| `collection` | Required for Collection operations. Specifies the Collection slug to operate against. | -| `data` | The data to use within the operation. Required for `create`, `update`. | -| `depth` | [Control auto-population](/docs/getting-started/concepts#depth) of nested relationship and upload fields. | -| `locale` | Specify [locale](/docs/configuration/localization) for any returned documents. | -| `fallbackLocale` | Specify a [fallback locale](/docs/configuration/localization) to use for any returned documents. | -| `overrideAccess` | Skip access control. By default, this property is set to false. | -| `user` | If you re-enable access control, you can specify a user to use against the access control checks. | -| `showHiddenFields` | Opt-in to receiving hidden fields. By default, they are hidden from returned documents in accordance to your config. | +| Local Option | Description | +| -------------------- | ------------ | +| `collection` | Required for Collection operations. Specifies the Collection slug to operate against. | +| `data` | The data to use within the operation. Required for `create`, `update`. | +| `depth` | [Control auto-population](/docs/getting-started/concepts#depth) of nested relationship and upload fields. | +| `locale` | Specify [locale](/docs/configuration/localization) for any returned documents. | +| `fallbackLocale` | Specify a [fallback locale](/docs/configuration/localization) to use for any returned documents. | +| `overrideAccess` | Skip access control. By default, this property is set to false. | +| `user` | If you re-enable access control, you can specify a user to use against the access control checks. | +| `showHiddenFields` | Opt-in to receiving hidden fields. By default, they are hidden from returned documents in accordance to your config. | -_There are more options available on an operation by operation basis outlined below._ +*There are more options available on an operation by operation basis outlined below.* - Note: -
    - By default, all access control checks are disabled in the Local API, but you - can re-enable them if you'd like, as well as pass a specific user to run the - operation with. + Note:
    + By default, all access control checks are disabled in the Local API, but you can re-enable them if you'd like, as well as pass a specific user to run the operation with.
    ## Collections @@ -93,13 +82,12 @@ The following Collection operations are available through the Local API: ```js // The created Post document is returned const post = await payload.create({ - collection: "posts", // required - data: { - // required - title: "sure", - description: "maybe", + collection: 'posts', // required + data: { // required + title: 'sure', + description: 'maybe', }, - locale: "en", + locale: 'en', fallbackLocale: false, user: dummyUserDoc, overrideAccess: true, @@ -108,7 +96,7 @@ const post = await payload.create({ // If creating verification-enabled auth doc, // you can optionally disable the email that is auto-sent disableVerificationEmail: true, -}); +}) ``` #### Find @@ -136,15 +124,15 @@ const result = await payload.find({ ```js // Result will be a Post document. const result = await payload.findByID({ - collection: "posts", // required - id: "507f1f77bcf86cd799439011", // required + collection: 'posts', // required + id: '507f1f77bcf86cd799439011', // required depth: 2, - locale: "en", + locale: 'en', fallbackLocale: false, user: dummyUser, overrideAccess: false, showHiddenFields: true, -}); +}) ``` #### Update @@ -152,20 +140,19 @@ const result = await payload.findByID({ ```js // Result will be the updated Post document. const result = await payload.update({ - collection: "posts", // required - id: "507f1f77bcf86cd799439011", // required - data: { - // required - title: "sure", - description: "maybe", + collection: 'posts', // required + id: '507f1f77bcf86cd799439011', // required + data: { // required + title: 'sure', + description: 'maybe', }, depth: 2, - locale: "en", + locale: 'en', fallbackLocale: false, user: dummyUser, overrideAccess: false, showHiddenFields: true, -}); +}) ``` #### Delete @@ -173,15 +160,15 @@ const result = await payload.update({ ```js // Result will be the now-deleted Post document. const result = await payload.delete({ - collection: "posts", // required - id: "507f1f77bcf86cd799439011", // required + collection: 'posts', // required + id: '507f1f77bcf86cd799439011', // required depth: 2, - locale: "en", + locale: 'en', fallbackLocale: false, user: dummyUser, overrideAccess: false, showHiddenFields: true, -}); +}) ``` ## Auth Operations @@ -199,20 +186,19 @@ If a collection has [`Authentication`](/docs/authentication/overview) enabled, a // } const result = await payload.login({ - collection: "users", // required - data: { - // required - email: "dev@payloadcms.com", - password: "rip", + collection: 'users', // required + data: { // required + email: 'dev@payloadcms.com', + password: 'rip', }, req: req, // pass an Express `req` which will be provided to all hooks res: res, // used to automatically set an HTTP-only auth cookie depth: 2, - locale: "en", + locale: 'en', fallbackLocale: false, overrideAccess: false, showHiddenFields: true, -}); +}) ``` #### Forgot Password @@ -220,13 +206,12 @@ const result = await payload.login({ ```js // Returned token will allow for a password reset const token = await payload.forgotPassword({ - collection: "users", // required - data: { - // required - email: "dev@payloadcms.com", + collection: 'users', // required + data: { // required + email: 'dev@payloadcms.com', }, req: req, // pass an Express `req` which will be provided to all hooks -}); +}) ``` #### Reset Password @@ -238,14 +223,13 @@ const token = await payload.forgotPassword({ // user: { ... } // the user document that just logged in // } const result = await payload.forgotPassword({ - collection: "users", // required - data: { - // required - token: "afh3o2jf2p3f...", // the token generated from the forgotPassword operation + collection: 'users', // required + data: { // required + token: 'afh3o2jf2p3f...', // the token generated from the forgotPassword operation }, req: req, // pass an Express `req` which will be provided to all hooks res: res, // used to automatically set an HTTP-only auth cookie -}); +}) ``` #### Unlock @@ -253,14 +237,13 @@ const result = await payload.forgotPassword({ ```js // Returned result will be a boolean representing success or failure const result = await payload.unlock({ - collection: "users", // required - data: { - // required - email: "dev@payloadcms.com", + collection: 'users', // required + data: { // required + email: 'dev@payloadcms.com', }, req: req, // pass an Express `req` which will be provided to all hooks overrideAccess: true, -}); +}) ``` #### Verify @@ -268,9 +251,9 @@ const result = await payload.unlock({ ```js // Returned result will be a boolean representing success or failure const result = await payload.verify({ - collection: "users", // required - token: "afh3o2jf2p3f...", // the token saved on the user as `_verificationToken` -}); + collection: 'users', // required + token: 'afh3o2jf2p3f...', // the token saved on the user as `_verificationToken` +}) ``` ## Globals @@ -282,14 +265,14 @@ The following Global operations are available through the Local API: ```js // Result will be the Header Global. const result = await payload.findGlobal({ - global: "header", // required + global: 'header', // required depth: 2, - locale: "en", + locale: 'en', fallbackLocale: false, user: dummyUser, overrideAccess: false, showHiddenFields: true, -}); +}) ``` #### Update @@ -297,23 +280,22 @@ const result = await payload.findGlobal({ ```js // Result will be the updated Header Global. const result = await payload.updateGlobal({ - global: "header", // required - data: { - // required + global: 'header', // required + data: { // required nav: [ { - url: "https://google.com", + url: 'https://google.com', }, { - url: "https://payloadcms.com", + url: 'https://payloadcms.com', }, ], }, depth: 2, - locale: "en", + locale: 'en', fallbackLocale: false, user: dummyUser, overrideAccess: false, showHiddenFields: true, -}); +}) ``` diff --git a/docs/production/deployment.mdx b/docs/production/deployment.mdx index cdbed17b17..bd2b2cd9d0 100644 --- a/docs/production/deployment.mdx +++ b/docs/production/deployment.mdx @@ -7,9 +7,7 @@ keywords: deployment, production, config, configuration, documentation, Content --- - So you've developed a Payload app, it's fully tested, and running great - locally. Now it's time to launch. Awesome! Great work! Now, - what's next? + So you've developed a Payload app, it's fully tested, and running great locally. Now it's time to launch. Awesome! Great work! Now, what's next? There are many ways to deploy Payload to a production environment. When evaluating how you will deploy Payload, you need to consider these main aspects: @@ -31,13 +29,7 @@ When you initialize Payload, you provide it with a `secret` property. This prope Because _**you**_ are in complete control of who can do what with your data, you should double and triple-check that you wield that power responsibly before deploying to Production. - - By default, all Access Control functions require that a user is successfully - logged in to Payload to create, read, update, or delete data. - {" "} - But, if you allow public user registration, for example, you will want to make - sure that your access control functions are more strict - permitting{" "} - only appropriate users to perform appropriate actions. + By default, all Access Control functions require that a user is successfully logged in to Payload to create, read, update, or delete data. But, if you allow public user registration, for example, you will want to make sure that your access control functions are more strict - permitting only appropriate users to perform appropriate actions. ##### Building the Admin panel @@ -45,7 +37,6 @@ Because _**you**_ are in complete control of who can do what with your data, you Before running in Production, you need to have built a production-ready copy of the Payload Admin panel. To do this, Payload provides the `build` NPM script. You can use it by adding a `script` to your `package.json` file like this: `package.json`: - ```js { "name": "project-name-here", @@ -104,18 +95,15 @@ Alternatively, persistent filesystems will never delete your files and can be tr - Many other more traditional web hosts - Warning: -
    - If you rely on Payload's Upload functionality, make sure you - either use a host with a persistent filesystem or have an integration with a - third-party file host like Amazon S3. + Warning:
    + If you rely on Payload's Upload functionality, make sure you either use a host with a persistent filesystem or have an integration with a third-party file host like Amazon S3.
    ##### Using ephemeral filesystem providers like Heroku If you don't use Payload's `upload` functionality, you can go ahead and use Heroku or similar platform easily. Everything will work exactly as you want it to. -But, if you do, and you still want to use an ephemeral filesystem provider, you can write a hook-based solution to _copy_ the files your users upload to a more permanent storage solution like Amazon S3 or DigitalOcean Spaces. +But, if you do, and you still want to use an ephemeral filesystem provider, you can write a hook-based solution to *copy* the files your users upload to a more permanent storage solution like Amazon S3 or DigitalOcean Spaces. **To automatically send uploaded files to S3 or similar, you could:** diff --git a/docs/production/licensing.mdx b/docs/production/licensing.mdx index a0af675d6e..37b6ac5295 100644 --- a/docs/production/licensing.mdx +++ b/docs/production/licensing.mdx @@ -16,9 +16,8 @@ Payload is free to use locally for development purposes for as long as you like. 1. Add your license to a `.env` variable, and then add the `license` property to your `payload.init()` call. `server.js`: - ```js -const payload = require("payload"); +const payload = require('payload'); payload.init({ license: process.env.PAYLOAD_LICENSE_KEY, @@ -33,17 +32,13 @@ payload.init({ Payload licensing is enforced only through its Admin panel. Each time the Admin panel is loaded, a request is made to our licensing server that evaluates the domain that the panel was loaded from. We then verify that you have a valid, active license key and that the domain being used matches the license accordingly. - Note: -
    - Your Payload APIs will always be available, regardless of subscription status. - This means you can have peace of mind that your critical operations relying on - your API will not going to be hindered because of a lapse in billing issue or - a network problem between systems. Only the Admin panel will be affected. + Note:
    + Your Payload APIs will always be available, regardless of subscription status. This means you can have peace of mind that your critical operations relying on your API will not going to be hindered because of a lapse in billing issue or a network problem between systems. Only the Admin panel will be affected.
    ### How to choose the domain for your license -Payload licenses are specific to **one** domain, but you can use your Payload API from an unlimited amount of sources. However, you can _only access your Payload Admin panel from one domain_. This means that when you are selecting the domain you'd like to tie to your Payload license, you should choose the domain that you'd like to use to access your admin panel in production. +Payload licenses are specific to **one** domain, but you can use your Payload API from an unlimited amount of sources. However, you can *only access your Payload Admin panel from one domain*. This means that when you are selecting the domain you'd like to tie to your Payload license, you should choose the domain that you'd like to use to access your admin panel in production. **Examples:** @@ -51,10 +46,8 @@ Payload licenses are specific to **one** domain, but you can use your Payload AP - If you'd like to access via a root-level domain like `coolsitehere.com/admin`, you would use `coolsitehere.com` for your license. - Note: -
    - Even though your Payload license is tied to one domain, you can use your Admin - panel for dev purposes however and wherever you'd like. + Note:
    + Even though your Payload license is tied to one domain, you can use your Admin panel for dev purposes however and wherever you'd like.
    #### How does Payload know if the license is being used for dev or production purposes? @@ -72,5 +65,4 @@ Our licensing service checks for any of the following criteria to determine if y 1. **Can I transfer a license?** You can change the domain name of a license in your Payload account by clicking on the license domain name, finding the "Change domain" link and following the instructions. If you need to transfer ownership to another user or organization, you can [contact us](mailto:info@payloadcms.com) for help. ### Read the full license - You can read the entirety of the Payload license directly in the distributed NPM package or in the Payload source code at [github.com](https://github.com/payloadcms/payload/blob/master/license.md) diff --git a/docs/production/preventing-abuse.mdx b/docs/production/preventing-abuse.mdx index d8f3ff1fc7..4104dee77e 100644 --- a/docs/production/preventing-abuse.mdx +++ b/docs/production/preventing-abuse.mdx @@ -18,22 +18,16 @@ Set the max number of failed login attempts before a user account is locked out To prevent DDoS, brute-force, and similar attacks, you can set IP-based rate limits so that once a certain threshold of requests has been hit by a single IP, further requests from the same IP will be ignored. The Payload config `rateLimit` property accepts an object with the following properties: -| Option | Description | -| ---------------- | ---------------------------------------------------------------------------------------------------------------------- | -| **`window`** | Time in milliseconds to track requests per IP | -| **`max`** | Number of requests served from a single IP before limiting | -| **`skip`** | Express middleware function that can return true (or promise resulting in true) that will bypass limit | -| **`trustProxy`** | True or false, to enable to allow requests to pass through a proxy such as a load balancer or an `nginx` reverse proxy | +| Option | Description | +| ---------------------------- | -------------| +| **`window`** | Time in milliseconds to track requests per IP | +| **`max`** | Number of requests served from a single IP before limiting | +| **`skip`** | Express middleware function that can return true (or promise resulting in true) that will bypass limit | +| **`trustProxy`** | True or false, to enable to allow requests to pass through a proxy such as a load balancer or an `nginx` reverse proxy | - Warning: -
    - Very commonly, NodeJS apps are served behind `nginx` reverse proxies and - similar. If you use rate-limiting while you're behind a proxy,{" "} - all IP addresses from everyone that uses your API will appear - as if they are from a local origin (127.0.0.1), and your users will get - rate-limited very quickly without cause. If you plan to host your app behind a - proxy, make sure you set trustProxy to true. + Warning:
    + Very commonly, NodeJS apps are served behind `nginx` reverse proxies and similar. If you use rate-limiting while you're behind a proxy, all IP addresses from everyone that uses your API will appear as if they are from a local origin (127.0.0.1), and your users will get rate-limited very quickly without cause. If you plan to host your app behind a proxy, make sure you set trustProxy to true.
    #### Max Depth @@ -49,7 +43,6 @@ CSRF prevention will verify the authenticity of each request to your API to prev To securely allow headless operation you will need to configure the allowed origins for requests to be able to use the Payload API. You can see how to set CORS as well as other payload configuration settings [here](http://localhost:3000/docs/configuration/overview) ### Limiting GraphQL Complexity - Because GraphQL gives the power of query writing outside a server's control, someone with bad intentions might write a maliciously complex query and bog down your server. To prevent resource-intensive GraphQL requests, Payload provides a way specify complexity limits which are based on a complexity score that is calculated for each request. Any GraphQL request that is calculated to be too expensive is rejected. On the Payload config, in `graphQL` you can set the `maxComplexity` value as an integer. For reference, the default complexity value for each added field is 1, and all `relationship` and `upload` fields are assigned a value of 10. diff --git a/docs/queries/overview.mdx b/docs/queries/overview.mdx index 1b09d3582c..a4fddbca74 100644 --- a/docs/queries/overview.mdx +++ b/docs/queries/overview.mdx @@ -9,15 +9,7 @@ keywords: query, documents, overview, documentation, Content Management System, Payload provides an extremely granular querying language through all APIs. Each API takes the same syntax and fully supports all options. - - Here, "querying" relates to filtering or searching through documents within - a Collection. - {" "} - You can build queries to pass to Find operations as well as to{" "} - - restrict which documents certain users can access - {" "} - via access control functions. + Here, "querying" relates to filtering or searching through documents within a Collection. You can build queries to pass to Find operations as well as to restrict which documents certain users can access via access control functions. ### Simple queries @@ -26,54 +18,55 @@ For example, say you have a collection as follows: ```js const Post = { - slug: "posts", + slug: 'posts', fields: [ { - name: "color", - type: "select", - options: ["mint", "dark-gray", "white"], + name: 'color', + type: 'select', + options: [ + 'mint', + 'dark-gray', + 'white', + ], }, { - name: "featured", - type: "checkbox", - }, - ], -}; + name: 'featured', + type: 'checkbox', + } + ] +} ``` You may eventually have a lot of documents within this Collection. If you wanted to find only documents with `color` equal to `mint`, you could write a query as follows: ```js const query = { - color: { - // property name to filter on - equals: "mint", // operator to use and value to compare against + color: { // property name to filter on + equals: 'mint', // operator to use and value to compare against }, -}; +} ``` The above example demonstrates a simple query but you can get much more complex. ### Operators -| Operator | Description | -| -------------------- | ----------------------------------------------------------------------------------------- | -| `equals` | The value must be exactly equal. | -| `not_equals` | The query will return all documents where the value is not equal. | -| `greater_than` | For numeric or date-based fields. | -| `greater_than_equal` | For numeric or date-based fields. | -| `less_than` | For numeric or date-based fields. | -| `less_than_equal` | For numeric or date-based fields. | -| `like` | The value must partially match. | -| `in` | The value must be found within the provided comma-delimited list of values. | -| `not_in` | The value must NOT be within the provided comma-delimited list of values. | +| Operator | Description | +| -------------------- | ------------ | +| `equals` | The value must be exactly equal. | +| `not_equals` | The query will return all documents where the value is not equal. | +| `greater_than` | For numeric or date-based fields. | +| `greater_than_equal` | For numeric or date-based fields. | +| `less_than` | For numeric or date-based fields. | +| `less_than_equal` | For numeric or date-based fields. | +| `like` | The value must partially match. | +| `in` | The value must be found within the provided comma-delimited list of values. | +| `not_in` | The value must NOT be within the provided comma-delimited list of values. | | `exists` | Only return documents where the value either exists (`true`) or does not exist (`false`). | - Tip:
    - If you know your users will be querying on certain fields a lot, you can add - index: true - to a field's config which will speed up searches using that field immensely. + Tip:
    + If you know your users will be querying on certain fields a lot, you can add index: true to a field's config which will speed up searches using that field immensely.
    ### And / Or Logic @@ -82,30 +75,28 @@ In addition to defining simple queries, you can join multiple queries together u ```js const query = { - or: [ - // array of OR conditions + or: [ // array of OR conditions { color: { - equals: "mint", + equals: 'mint', }, }, { - and: [ - // nested array of AND conditions + and: [ // nested array of AND conditions { color: { - equals: "white", - }, + equals: 'white', + } }, { featured: { equals: false, - }, - }, - ], - }, - ], -}; + } + } + ] + } + ] +} ``` Written in plain English, if the above query were passed to a `find` operation, it would translate to finding posts where either the `color` is `mint` OR the `color` is `white` AND `featured` is set to false. @@ -140,29 +131,24 @@ This one isn't too bad, but more complex queries get unavoidably more difficult **For example, using fetch:** ```js -import qs from "qs"; +import qs from 'qs'; const query = { color: { - equals: "mint", + equals: 'mint', }, // This query could be much more complex // and QS would handle it beautifully -}; +} const getPosts = async () => { - const stringifiedQuery = qs.stringify( - { - where: query, // ensure that `qs` adds the `where` property, too! - }, - { addQueryPrefix: true } - ); + const stringifiedQuery = qs.stringify({ + where: query // ensure that `qs` adds the `where` property, too! + }, { addQueryPrefix: true }); - const response = await fetch( - `http://localhost:3000/api/posts${stringifiedQuery}` - ); + const response = await fetch(`http://localhost:3000/api/posts${stringifiedQuery}`); // Continue to handle the response below... -}; +} ``` ### Local API Queries @@ -172,18 +158,19 @@ The Local API's `find` operation accepts an object exactly how you write it. For ```js const getPosts = async () => { const posts = await payload.find({ - collection: "posts", + collection: 'posts', where: { color: { - equals: "mint", + equals: 'mint', }, }, }); return posts; -}; +} ``` + ## Sort Payload `find` queries support a `sort` parameter through all APIs. Pass the `name` of a top-level field to sort by that field in ascending order. Prefix the name of the field with a minus symbol ("-") to sort in descending order. @@ -192,7 +179,6 @@ Payload `find` queries support a `sort` parameter through all APIs. Pass the `na **`https://localhost:3000/api/posts?sort=-createdAt`** **GraphQL example:** - ``` query { Posts(sort: "-createdAt") { @@ -208,10 +194,10 @@ query { ```js const getPosts = async () => { const posts = await payload.find({ - collection: "posts", - sort: "-createdAt", + collection: 'posts', + sort: '-createdAt', }); return posts; -}; +} ``` diff --git a/docs/queries/pagination.mdx b/docs/queries/pagination.mdx index 0dc38b374f..665cfe9751 100644 --- a/docs/queries/pagination.mdx +++ b/docs/queries/pagination.mdx @@ -10,21 +10,20 @@ All collection `find` queries are paginated automatically. Responses are returne **`Find` response properties:** -| Property | Description | -| ------------- | --------------------------------------------------------- | -| docs | Array of documents in the collection | -| totalDocs | Total available documents within the collection | -| limit | Limit query parameter - defaults to `10` | -| totalPages | Total pages available, based upon the `limit` queried for | -| page | Current page number | -| pagingCounter | `number` of the first doc on the current page | -| hasPrevPage | `true/false` if previous page exists | -| hasNextPage | `true/false` if next page exists | -| prevPage | `number` of previous page, `null` if it doesn't exist | -| nextPage | `number` of next page, `null` if it doesn't exist | +| Property | Description | +| ------------- | ---------------------------------------------------------- | +| docs | Array of documents in the collection | +| totalDocs | Total available documents within the collection | +| limit | Limit query parameter - defaults to `10` | +| totalPages | Total pages available, based upon the `limit` queried for | +| page | Current page number | +| pagingCounter | `number` of the first doc on the current page | +| hasPrevPage | `true/false` if previous page exists | +| hasNextPage | `true/false` if next page exists | +| prevPage | `number` of previous page, `null` if it doesn't exist | +| nextPage | `number` of next page, `null` if it doesn't exist | **Example response:** - ```js { // Document Array // highlight-line @@ -55,7 +54,7 @@ All collection `find` queries are paginated automatically. Responses are returne All Payload APIs support the pagination controls below. With them, you can create paginated lists of documents within your application: -| Control | Description | -| ------- | --------------------------------------- | -| `limit` | Limits the number of documents returned | -| `page` | Get a specific page number | +| Control | Description | +| --------- | ----------------------------------------------------------------------------------------- | +| `limit` | Limits the number of documents returned | +| `page` | Get a specific page number | diff --git a/docs/rest-api/overview.mdx b/docs/rest-api/overview.mdx index 031bd1b54b..9b16f54aa0 100644 --- a/docs/rest-api/overview.mdx +++ b/docs/rest-api/overview.mdx @@ -7,8 +7,7 @@ keywords: rest, api, documentation, Content Management System, cms, headless, ja --- - A fully functional REST API is automatically generated from your Collection - and Global configs. + A fully functional REST API is automatically generated from your Collection and Global configs. All Payload API routes are mounted prefixed to your config's `routes.api` URL segment (default: `/api`). @@ -25,13 +24,13 @@ Each collection is mounted using its `slug` value. For example, if a collection' **All CRUD operations are exposed as follows:** -| Method | Path | Description | -| -------- | --------------------------- | --------------------------------- | -| `GET` | `/api/{collectionSlug}` | Find paginated documents | -| `GET` | `/api/{collectionSlug}/:id` | Find a specific document by ID | -| `POST` | `/api/{collectionSlug}` | Create a new document | -| `PUT` | `/api/{collectionSlug}/:id` | Update a document by ID | -| `DELETE` | `/api/{collectionSlug}/:id` | Delete an existing document by ID | +| Method | Path | Description | +| -------- | --------------------------- | -------------------------------------- | +| `GET` | `/api/{collectionSlug}` | Find paginated documents | +| `GET` | `/api/{collectionSlug}/:id` | Find a specific document by ID | +| `POST` | `/api/{collectionSlug}` | Create a new document | +| `PUT` | `/api/{collectionSlug}/:id` | Update a document by ID | +| `DELETE` | `/api/{collectionSlug}/:id` | Delete an existing document by ID | ##### Additional `find` query parameters @@ -44,22 +43,22 @@ The `find` endpoint supports the following additional query parameters: ## Auth Operations -| Method | Path | Description | -| ------ | --------------------------------------- | --------------------------------------------------------------------------------------- | -| `POST` | `/api/{collectionSlug}/verify/:token` | [Email verification](/docs/authentication/operations#verify-by-email), if enabled. | -| `POST` | `/api/{collectionSlug}/unlock` | [Unlock a user's account](/docs/authentication/operations#unlock), if enabled. | -| `POST` | `/api/{collectionSlug}/login` | [Logs in](/docs/authentication/operations#login) a user with email / password. | -| `POST` | `/api/{collectionSlug}/logout` | [Logs out](/docs/authentication/operations#logout) a user. | -| `POST` | `/api/{collectionSlug}/refresh-token` | [Refreshes a token](/docs/authentication/operations#refresh) that has not yet expired. | -| `GET` | `/api/{collectionSlug}/me` | [Returns the currently logged in user with token](/docs/authentication/operations#me). | -| `POST` | `/api/{collectionSlug}/forgot-password` | [Password reset workflow](/docs/authentication/operations#forgot-password) entry point. | -| `POST` | `/api/{collectionSlug}/reset-password` | [To reset the user's password](/docs/authentication/operations#reset-password). | +| Method | Path | Description | +| -------- | --------------------------- | ----------- | +| `POST` | `/api/{collectionSlug}/verify/:token` | [Email verification](/docs/authentication/operations#verify-by-email), if enabled. | +| `POST` | `/api/{collectionSlug}/unlock` | [Unlock a user's account](/docs/authentication/operations#unlock), if enabled. | +| `POST` | `/api/{collectionSlug}/login` | [Logs in](/docs/authentication/operations#login) a user with email / password. | +| `POST` | `/api/{collectionSlug}/logout` | [Logs out](/docs/authentication/operations#logout) a user. | +| `POST` | `/api/{collectionSlug}/refresh-token` | [Refreshes a token](/docs/authentication/operations#refresh) that has not yet expired. | +| `GET` | `/api/{collectionSlug}/me` | [Returns the currently logged in user with token](/docs/authentication/operations#me). | +| `POST` | `/api/{collectionSlug}/forgot-password` | [Password reset workflow](/docs/authentication/operations#forgot-password) entry point. | +| `POST` | `/api/{collectionSlug}/reset-password` | [To reset the user's password](/docs/authentication/operations#reset-password). | ## Globals Globals cannot be created or deleted, so there are only two REST endpoints opened: -| Method | Path | Description | -| ------ | --------------------------- | ----------------------- | -| `GET` | `/api/globals/{globalSlug}` | Get a global by slug | -| `POST` | `/api/globals/{globalSlug}` | Update a global by slug | +| Method | Path | Description | +| -------- | --------------------------- | ----------------------- | +| `GET` | `/api/globals/{globalSlug}` | Get a global by slug | +| `POST` | `/api/globals/{globalSlug}` | Update a global by slug | diff --git a/docs/upload/overview.mdx b/docs/upload/overview.mdx index 9764d8c93f..c1a4a711b5 100644 --- a/docs/upload/overview.mdx +++ b/docs/upload/overview.mdx @@ -7,13 +7,11 @@ keywords: uploads, images, media, overview, documentation, Content Management Sy --- - Payload provides for everything you need to enable file upload, storage, and - management directly on your server—including extremely powerful file access - control. + Payload provides for everything you need to enable file upload, storage, and management directly on your server—including extremely powerful file access control. ![Upload admin panel functionality](https://payloadcms.com/images/upload-admin.jpg) -_Admin panel screenshot depicting a Media Collection with Upload enabled_ +*Admin panel screenshot depicting a Media Collection with Upload enabled* **Here are some common use cases of Uploads:** @@ -24,7 +22,7 @@ _Admin panel screenshot depicting a Media Collection with Upload enabled_ **By simply enabling Upload functionality on a Collection, Payload will automatically transform your Collection into a robust file management / storage solution. The following modifications will be made:** 1. `filename`, `mimeType`, and `filesize` fields will be automatically added to your Collection. Optionally, if you pass `imageSizes` to your Collection's Upload config, a [`sizes`](#image-sizes) array will also be added containing auto-resized image sizes and filenames. -1. The Admin panel will modify its built-in `List` component to show a thumbnail gallery of your Uploads instead of the default Table view +1. The Admin panel will modify its built-in `List` component to show a thumbnail gallery of your Uploads instead of the default Table view 1. The Admin panel will modify its `Edit` view(s) to add a new set of corresponding Upload UI which will allow for file upload 1. The `create`, `update`, and `delete` Collection operations will be modified to support file upload, re-upload, and deletion @@ -33,47 +31,45 @@ _Admin panel screenshot depicting a Media Collection with Upload enabled_ Every Payload Collection can opt-in to supporting Uploads by specifying the `upload` property on the Collection's config to either `true` or to an object containing `upload` options. - Tip: -
    A common pattern is to create a Media collection and - enable upload on that collection. + Tip:
    + A common pattern is to create a Media collection and enable upload on that collection.
    #### Collection Upload Options -| Option | Description | -| -------------------- | ------------------------------------------------------------------------------------------------------------------------------------- | -| **`staticURL`** \* | The base URL path to use to access you uploads. Example: `/media` | -| **`staticDir`** \* | The folder directory to use to store media in. Can be either an absolute path or relative to the directory that contains your config. | -| **`imageSizes`** | If specified, image uploads will be automatically resized in accordance to these image sizes. [More](#image-sizes) | -| **`adminThumbnail`** | Which of your provided image sizes to use for the admin panel's thumbnail. Typically a size around 500x500px or so works well. | +| Option | Description | +| ---------------------- | -------------| +| **`staticURL`** * | The base URL path to use to access you uploads. Example: `/media` | +| **`staticDir`** * | The folder directory to use to store media in. Can be either an absolute path or relative to the directory that contains your config. | +| **`imageSizes`** | If specified, image uploads will be automatically resized in accordance to these image sizes. [More](#image-sizes) | +| **`adminThumbnail`** | Which of your provided image sizes to use for the admin panel's thumbnail. Typically a size around 500x500px or so works well. | -_An asterisk denotes that a property above is required._ +*An asterisk denotes that a property above is required.* **Example Upload collection:** - ```js const Media = { - slug: "media", + slug: 'media', upload: { - staticURL: "/media", - staticDir: "media", + staticURL: '/media', + staticDir: 'media', imageSizes: [ { - name: "thumbnail", + name: 'thumbnail', width: 400, height: 300, - crop: "centre", + crop: 'centre', }, { - name: "card", + name: 'card', width: 768, height: 1024, - crop: "centre", - }, + crop: 'centre', + } ], - adminThumbnail: "thumbnail", - }, -}; + adminThumbnail: 'thumbnail', + } +} ``` ### Payload-wide Upload Options @@ -83,17 +79,17 @@ Payload relies on the [`express-fileupload`](https://www.npmjs.com/package/expre A common example of what you might want to customize within Payload-wide Upload options would be to increase the allowed `fileSize` of uploads sent to Payload: ```js -import { buildConfig } from "payload/config"; +import { buildConfig } from 'payload/config'; export default buildConfig({ - serverURL: "http://localhost:3000", + serverURL: 'http://localhost:3000', collections: [ { - slug: "media", + slug: 'media', fields: [ { - name: "alt", - type: "text", + name: 'alt', + type: 'text', }, ], upload: true, @@ -102,8 +98,8 @@ export default buildConfig({ upload: { limits: { fileSize: 5000000, // 5MB, written in bytes - }, - }, + } + } }); ``` @@ -118,11 +114,8 @@ Behind the scenes, Payload relies on [`sharp`](https://sharp.pixelplumbing.com/a ### Uploading Files - Important: -
    - Uploading files is currently only possible through the REST API due to how - GraphQL works. It's difficult and fairly nonsensical to support uploading - files through GraphQL. + Important:
    + Uploading files is currently only possible through the REST API due to how GraphQL works. It's difficult and fairly nonsensical to support uploading files through GraphQL.
    To upload a file, use your collection's [`create`](/docs/rest-api/overview#collections) endpoint. Send it all the data that your Collection requires, as well as a `file` key containing the file that you'd like to upload.