### Install Sentry using the Sentry Wizard Source: https://github.com/payloadcms/website/blob/main/public/llms-full.txt Use the Sentry installation wizard to automatically set up Sentry for your Next.js project. This is the recommended approach for a quick start. ```bash npx @sentry/wizard@latest -i nextjs ``` -------------------------------- ### Install Stripe Plugin Source: https://github.com/payloadcms/website/blob/main/public/llms-full.txt Install the Stripe plugin using pnpm, npm, or Yarn. ```bash pnpm add @payloadcms/plugin-stripe ``` -------------------------------- ### Plugin Configuration Example Source: https://github.com/payloadcms/website/blob/main/public/llms-full.txt Example of how to include a plugin in the Payload configuration, including options. ```typescript plugins: [ // when you rename the plugin or add options, make sure to update it here samplePlugin({ enabled: false, }) ] ``` -------------------------------- ### Install Live Preview React Package Source: https://github.com/payloadcms/website/blob/main/public/llms-full.txt Install the necessary package for live preview integration in React applications. ```bash npm install @payloadcms/live-preview-react ``` -------------------------------- ### Create Payload App with Example Source: https://github.com/payloadcms/website/blob/main/public/llms-full.txt Use `create-payload-app` to quickly set up a new project based on a specific example. ```bash npx create-payload-app --example example_name ``` -------------------------------- ### Configure Block Images with URL Strings Source: https://github.com/payloadcms/website/blob/main/public/llms-full.txt This example shows how to configure block images using only URL strings, omitting alt text for simpler setups. ```typescript const CallToActionBlock: Block = { slug: 'cta', admin: { images: { icon: 'https://example.com/icons/cta-20x20.svg', thumbnail: 'https://example.com/thumbnails/cta-block-480x320.jpg', }, }, fields: [ { name: 'buttonText', type: 'text', }, ], } ``` -------------------------------- ### Install R2 Storage Adapter Source: https://github.com/payloadcms/website/blob/main/public/llms-full.txt Install the R2 storage adapter package using pnpm. ```sh pnpm add @payloadcms/storage-r2 ``` -------------------------------- ### Install Cloud Storage Plugin Source: https://github.com/payloadcms/website/blob/main/public/llms-full.txt Install the cloud storage plugin package for creating custom storage adapters. ```sh `pnpm add @payloadcms/plugin-cloud-storage` ``` -------------------------------- ### Install Stripe SDK Source: https://github.com/payloadcms/website/blob/main/public/llms-full.txt Install the Stripe SDK package using pnpm. Payload does not install this automatically. ```bash pnpm add stripe ``` -------------------------------- ### Install Multi-Tenant Plugin Source: https://github.com/payloadcms/website/blob/main/public/llms-full.txt Install the @payloadcms/plugin-multi-tenant package using pnpm, npm, or Yarn. ```bash pnpm add @payloadcms/plugin-multi-tenant ``` -------------------------------- ### Install Live Preview Vue Package Source: https://github.com/payloadcms/website/blob/main/public/llms-full.txt Install the necessary package for Vue.js live preview integration. ```bash npm install @payloadcms/live-preview-vue ``` -------------------------------- ### Install and Configure a Sample Plugin Source: https://github.com/payloadcms/website/blob/main/public/llms-full.txt Demonstrates how to install a sample plugin by importing it and adding it to the `plugins` array in the Payload configuration. The plugin can be configured with options. ```typescript import samplePlugin from 'sample-plugin'; const config = buildConfig({ plugins: [ // Add plugins here samplePlugin({ enabled: true, }), ], }); export default config; ``` -------------------------------- ### Example Task with Schedule Source: https://github.com/payloadcms/website/blob/main/public/llms-full.txt Demonstrates how to define a task with a schedule configuration. This example sets up a 'SendDigestEmail' task to run nightly. ```typescript import type { TaskConfig } from 'payload' export const SendDigestEmail: TaskConfig<'SendDigestEmail'> = { slug: 'SendDigestEmail', schedule: [ { cron: '0 0 * * *', // Every day at midnight queue: 'nightly', }, ], handler: async () => { await sendDigestToAllUsers() }, } ``` -------------------------------- ### Local API Examples Source: https://github.com/payloadcms/website/blob/main/public/llms-full.txt Examples demonstrating how to use the `trash` option with the Local API to retrieve all documents, only trashed documents, or only non-trashed documents. ```APIDOC ### Examples #### Local API Return all documents including trashed: ```ts const result = await payload.find({ collection: 'posts', trash: true, }) ``` Return only trashed documents: ```ts const result = await payload.find({ collection: 'posts', trash: true, where: { deletedAt: { exists: true, }, }, }) ``` Return only non-trashed documents: ```ts const result = await payload.find({ collection: 'posts', trash: false, }) ``` ``` -------------------------------- ### Install Base Live Preview Package Source: https://github.com/payloadcms/website/blob/main/public/llms-full.txt Install the core `@payloadcms/live-preview` package to build custom live preview components for any front-end framework. ```bash npm install @payloadcms/live-preview ``` -------------------------------- ### Install Import Export Plugin Source: https://github.com/payloadcms/website/blob/main/public/llms-full.txt Install the plugin using a JavaScript package manager like pnpm, npm, or Yarn. ```bash pnpm add @payloadcms/plugin-import-export ``` -------------------------------- ### Install Rich Text Lexical Editor Source: https://github.com/payloadcms/website/blob/main/public/llms-full.txt Install the Lexical-based rich text editor package using pnpm. ```bash pnpm install @payloadcms/richtext-lexical ``` -------------------------------- ### REST API Examples Source: https://github.com/payloadcms/website/blob/main/public/llms-full.txt Examples demonstrating how to use the `trash` query parameter with the REST API to retrieve all documents, only trashed documents, or only non-trashed documents. ```APIDOC #### REST Return **all** documents including trashed: ```http GET /api/posts?trash=true ``` Return **only trashed** documents: ```http GET /api/posts?trash=true&where[deletedAt][exists]=true ``` Return only non-trashed documents: ```http GET /api/posts?trash=false ``` ``` -------------------------------- ### Install Core Payload and Next.js Packages Source: https://github.com/payloadcms/website/blob/main/public/llms-full.txt Install the essential Payload packages and the Next.js integration package for your project. ```bash pnpm i payload @payloadcms/next ``` -------------------------------- ### Install Nested Docs Plugin Source: https://github.com/payloadcms/website/blob/main/public/llms-full.txt Install the plugin using pnpm, npm, or Yarn. This command adds the necessary package to your project dependencies. ```bash pnpm add @payloadcms/plugin-nested-docs ``` -------------------------------- ### Install Postgres Database Adapter Source: https://github.com/payloadcms/website/blob/main/public/llms-full.txt Install the Postgres database adapter to connect Payload CMS with a PostgreSQL database. ```bash pnpm i @payloadcms/db-postgres ``` -------------------------------- ### REST API Example Source: https://github.com/payloadcms/website/blob/main/public/llms-full.txt Example of how to fetch data from the REST API for a 'pages' collection. ```APIDOC ## REST API By default, the Payload REST API is mounted automatically for you at the `/api` path of your app. For example, if you have a Collection called `pages`: ```ts fetch('https://localhost:3000/api/pages') .then((res) => res.json()) .then((data) => console.log(data)) ``` For more information about the REST API, refer to the [REST API overview](../rest-api/overview). ``` -------------------------------- ### Install MongoDB Database Adapter Source: https://github.com/payloadcms/website/blob/main/public/llms-full.txt Install the MongoDB database adapter to connect Payload CMS with a MongoDB database. ```bash pnpm i @payloadcms/db-mongodb ``` -------------------------------- ### Install Payload Search Plugin Source: https://github.com/payloadcms/website/blob/main/public/llms-full.txt Install the plugin using pnpm, npm, or Yarn. This command adds the necessary package to your project. ```bash pnpm add @payloadcms/plugin-search ``` -------------------------------- ### Install S3 Storage Adapter Source: https://github.com/payloadcms/website/blob/main/public/llms-full.txt Install the S3 storage adapter for Payload CMS using pnpm. ```sh pnpm add @payloadcms/storage-s3 ``` -------------------------------- ### Install SQLite Database Adapter Source: https://github.com/payloadcms/website/blob/main/public/llms-full.txt Install the SQLite database adapter to connect Payload CMS with an SQLite database. ```bash pnpm i @payloadcms/db-sqlite ``` -------------------------------- ### MCP Tools List Request Example Source: https://github.com/payloadcms/website/blob/main/public/llms-full.txt Example of a cURL request to list MCP tools, including necessary headers like Authorization and Content-Type. Ensure the API key is valid. ```bash curl -i 'http://localhost:3000/api/mcp' \ -X POST \ -H 'Authorization: Bearer MCP-USER-API-KEY' \ -H 'Content-Type: application/json' \ -H 'Accept: application/json, text/event-stream' \ -d '{"jsonrpc":"2.0","id":"1","method":"tools/list","params":{}}' ``` -------------------------------- ### Install SEO Plugin with pnpm Source: https://github.com/payloadcms/website/blob/main/public/llms-full.txt Install the SEO plugin using pnpm. This command adds the necessary package to your project dependencies. ```bash pnpm add @payloadcms/plugin-seo ``` -------------------------------- ### Install Form Builder Plugin Source: https://github.com/payloadcms/website/blob/main/public/llms-full.txt Command to install the Payload Form Builder plugin using pnpm, npm, or Yarn. ```bash pnpm add @payloadcms/plugin-form-builder ``` -------------------------------- ### useLivePreview React Hook Example Source: https://github.com/payloadcms/website/blob/main/public/llms-full.txt An example implementation of a `useLivePreview` React hook that utilizes the core functions to manage live preview data. ```APIDOC ## `useLivePreview` React Hook Example This hook subscribes to Live Preview events, handles data merging, and updates the UI. ### Usage ```tsx import { subscribe, unsubscribe, ready } from '@payloadcms/live-preview' import { useCallback, useEffect, useState, useRef } from 'react' export const useLivePreview = (props: { depth?: number initialData: T serverURL: string }): { data: T isLoading: boolean } => { const { depth = 0, initialData, serverURL } = props const [data, setData] = useState(initialData) const [isLoading, setIsLoading] = useState(true) const hasSentReadyMessage = useRef(false) const onChange = useCallback((mergedData) => { setData(mergedData) setIsLoading(false) }, []) useEffect(() => { const subscription = subscribe({ callback: onChange, depth, initialData, serverURL, }) if (!hasSentReadyMessage.current) { hasSentReadyMessage.current = true ready({ serverURL, }) } return () => { unsubscribe(subscription) } }, [serverURL, onChange, depth, initialData]) return { data, isLoading, } } ``` ### Return Value - **`data`**: The current live preview data. - **`isLoading`**: A boolean indicating if the data is currently loading. ``` -------------------------------- ### Install Optional Payload Packages Source: https://github.com/payloadcms/website/blob/main/public/llms-full.txt Install optional packages for enhanced functionality like rich text editing, image manipulation, or GraphQL API support. ```bash pnpm i @payloadcms/richtext-lexical sharp graphql ``` -------------------------------- ### Example Workflow Handler Source: https://github.com/payloadcms/website/blob/main/public/llms-full.txt A simple example workflow handler demonstrating a sequence of tasks: creating a profile, sending an email, and adding to a list. This illustrates the flow that can be interrupted by task failures. ```typescript handler: async ({ job, tasks }) => { await tasks.createProfile('step1', { input: { userId: '123' } }) await tasks.sendEmail('step2', { input: { userId: '123' } }) await tasks.addToList('step3', { input: { userId: '123' } }) } ``` -------------------------------- ### Basic JSON Field Example Source: https://github.com/payloadcms/website/blob/main/public/llms-full.txt Demonstrates the basic setup of a JSON field within a Payload CMS collection configuration. This field is required and named 'customerJSON'. ```typescript import type { CollectionConfig } from 'payload' export const ExampleCollection: CollectionConfig = { slug: 'example-collection', fields: [ { name: 'customerJSON', // required type: 'json', // required required: true, }, ], } ``` -------------------------------- ### Example Custom List View Server Component Source: https://github.com/payloadcms/website/blob/main/public/llms-full.txt This is a basic example of a custom List View Server Component. It receives props from Payload and renders a simple div. ```tsx import React from 'react' import type { ListViewServerProps } from 'payload' export function MyCustomServerListView(props: ListViewServerProps) { return
This is a custom List View (Server)
} ``` -------------------------------- ### Setup Development Environment Source: https://github.com/payloadcms/website/blob/main/public/llms-full.txt Commands to create a new Payload project in a 'dev' folder for plugin development. ```bash mkdir dev cd dev npx create-payload-app@latest ``` -------------------------------- ### Dependency Mismatch Error Example Source: https://github.com/payloadcms/website/blob/main/public/llms-full.txt A common error indicating that different versions of Payload or React packages are installed, leading to issues like broken React context. ```bash TypeError: Cannot destructure property 'config' of... ``` -------------------------------- ### Use Preferences Hook in Custom Admin Component Source: https://github.com/payloadcms/website/blob/main/public/llms-full.txt Utilize the `usePreferences` hook to get and set user preferences. This example demonstrates storing and retrieving a list of last used colors. ```tsx 'use client' import React, { Fragment, useState, useEffect, useCallback } from 'react' import { usePreferences } from '@payloadcms/ui' const lastUsedColorsPreferenceKey = 'last-used-colors' export function CustomComponent() { const { getPreference, setPreference } = usePreferences() // Store the last used colors in local state const [lastUsedColors, setLastUsedColors] = useState([]) // Callback to add a color to the last used colors const updateLastUsedColors = useCallback( (color) => { // First, check if color already exists in last used colors. // If it already exists, there is no need to update preferences const colorAlreadyExists = lastUsedColors.indexOf(color) > -1 if (!colorAlreadyExists) { const newLastUsedColors = [...lastUsedColors, color] setLastUsedColors(newLastUsedColors) setPreference(lastUsedColorsPreferenceKey, newLastUsedColors) } }, [lastUsedColors, setPreference], ) // Retrieve preferences on component mount // This will only be run one time, because the `getPreference` method never changes useEffect(() => { const asyncGetPreference = async () => { const lastUsedColorsFromPreferences = await getPreference( lastUsedColorsPreferenceKey, ) setLastUsedColors(lastUsedColorsFromPreferences) } asyncGetPreference() }, [getPreference]) return (
{lastUsedColors && (
Last used colors:
    {lastUsedColors?.map((color) =>
  • {color}
  • )}
)}
) } ``` -------------------------------- ### Basic Sentry Plugin Setup in Payload Config Source: https://github.com/payloadcms/website/blob/main/public/llms-full.txt Integrate the Sentry plugin into your Payload CMS configuration by importing it and passing the Sentry instance. Ensure Sentry is installed and configured for Next.js beforehand. ```typescript import { buildConfig } from 'payload' import { sentryPlugin } from '@payloadcms/plugin-sentry' import { Pages, Media } from './collections' import * as Sentry from '@sentry/nextjs' const config = buildConfig({ collections: [Pages, Media], plugins: [sentryPlugin({ Sentry })], }) ``` -------------------------------- ### Implement initiatePayment with Stripe Source: https://github.com/payloadcms/website/blob/main/public/llms-full.txt This example shows how to implement the `initiatePayment` function using Stripe. It handles customer creation, payment intent creation, and database transaction recording. Ensure Stripe's secret key is securely managed. ```typescript import { PaymentAdapter, PaymentAdapterArgs, } from '@payloadcms/plugin-ecommerce' import Stripe from 'stripe' export const initiatePayment: NonNullable['initiatePayment'] = async ({ data, req, transactionsSlug }) => { const payload = req.payload // Check for any required data const currency = data.currency const cart = data.cart if (!currency) { throw new Error('Currency is required.') } const stripe = new Stripe(secretKey) try { let customer = ( await stripe.customers.list({ email: customerEmail, }) ).data[0] // Ensure stripe has a customer for this email if (!customer?.id) { customer = await stripe.customers.create({ email: customerEmail, }) } const shippingAddressAsString = JSON.stringify(shippingAddressFromData) const paymentIntent = await stripe.paymentIntents.create() // Create a transaction for the payment intent in the database const transaction = await payload.create({ collection: transactionsSlug, data: {}, }) // Return the client_secret so that the client can complete the payment const returnData: InitiatePaymentReturnType = { clientSecret: paymentIntent.client_secret || '', message: 'Payment initiated successfully', paymentIntentID: paymentIntent.id, } return returnData } catch (error) { payload.logger.error(error, 'Error initiating payment with Stripe') throw new Error( error instanceof Error ? error.message : 'Unknown error initiating payment', ) } } ``` -------------------------------- ### Global BeforeOperation Hook Example Source: https://github.com/payloadcms/website/blob/main/public/llms-full.txt Implement the 'beforeOperation' hook for global documents to modify operation arguments or execute side-effects before an operation starts. The hook receives arguments like 'args', 'operation', and 'req'. ```typescript import type { GlobalBeforeOperationHook } from 'payload' const beforeOperationHook: GlobalBeforeOperationHook = async ({ args, operation, req, }) => { return args // return modified operation arguments as necessary } ``` -------------------------------- ### Override GET Request with POST using Form Data Source: https://github.com/payloadcms/website/blob/main/public/llms-full.txt Perform a GET request using the POST method by setting the `X-Payload-HTTP-Method-Override` header to `GET`. Send parameters as `application/x-www-form-urlencoded` in the request body. ```typescript const res = await fetch(`${api}/${collectionSlug}`, { method: 'POST', credentials: 'include', headers: { 'Accept-Language': i18n.language, 'Content-Type': 'application/x-www-form-urlencoded', 'X-Payload-HTTP-Method-Override': 'GET', }, body: qs.stringify({ depth: 1, locale: 'en', }), }) ``` -------------------------------- ### Payload REST API SDK Initialization Source: https://github.com/payloadcms/website/blob/main/public/llms-full.txt Demonstrates how to install and initialize the Payload SDK for type-safe interaction with the Payload REST API. ```APIDOC ## Payload SDK Initialization ### Description Initialize the Payload SDK to interact with the REST API in a type-safe manner. The SDK can be installed via npm or pnpm. ### Installation ```bash pnpm add @payloadcms/sdk ``` ### Usage ```ts import { PayloadSDK } from '@payloadcms/sdk' const sdk = new PayloadSDK({ baseURL: 'https://example.com/api', }) ``` ### Usage with Manual Types For projects without a `payload-types.ts` file, or when working with multiple Payload configs, you can manually pass the types as a generic. ```ts import { PayloadSDK } from '@payloadcms/sdk' import type { Config } from './payload-types' // Adjust path as needed const sdk = new PayloadSDK({ baseURL: 'https://example.com/api', }) ``` ``` -------------------------------- ### Install @payloadcms/translations Package Source: https://github.com/payloadcms/website/blob/main/public/llms-full.txt Install the necessary package for I18n support using pnpm. ```bash pnpm install @payloadcms/translations ``` -------------------------------- ### Method Override for GET Requests (POST with URL Encoded Body) Source: https://github.com/payloadcms/website/blob/main/public/llms-full.txt Allows performing GET requests using the HTTP POST method by setting the `X-Payload-HTTP-Method-Override` header to `GET` and sending parameters as a URL-encoded form. ```APIDOC ## POST (with Method Override) ### Description This method allows you to send a GET request using the POST HTTP method. This is useful when query strings become too long. Parameters are sent as `application/x-www-form-urlencoded`. ### Method POST ### Endpoint `/${collectionSlug}` ### Headers - **X-Payload-HTTP-Method-Override** (string) - Required - Set to `GET`. - **Content-Type** (string) - Required - Set to `application/x-www-form-urlencoded`. - **Accept-Language** (string) - Optional - Language preference. ### Request Body (URL-encoded key-value pairs of query parameters) ### Request Example ```ts const res = await fetch(`${api}/${collectionSlug}`, { method: 'POST', credentials: 'include', headers: { 'Accept-Language': i18n.language, 'Content-Type': 'application/x-www-form-urlencoded', 'X-Payload-HTTP-Method-Override': 'GET', }, body: qs.stringify({ depth: 1, locale: 'en', }), }) ``` ### Response #### Success Response (200) (Response body of the equivalent GET request) ``` -------------------------------- ### Install Sentry Plugin Source: https://github.com/payloadcms/website/blob/main/public/llms-full.txt Install the @payloadcms/plugin-sentry package using your preferred JavaScript package manager. ```bash pnpm add @payloadcms/plugin-sentry ``` -------------------------------- ### Create Products Collection Source: https://github.com/payloadcms/website/blob/main/public/llms-full.txt Use `createProductsCollection` to set up the `products` collection. Configure access control, variants, currencies, and inventory tracking as needed. ```typescript import { createProductsCollection } from 'payload-plugin-ecommerce' const Products = createProductsCollection({ access: { isAdmin, adminOrPublishedStatus, }, enableVariants: true, currenciesConfig: { defaultCurrency: 'usd', currencies: [ { code: 'usd', symbol: '$', }, { code: 'eur', symbol: '€', }, ], }, inventory: { enabled: true, trackByVariant: true, lowStockThreshold: 5, }, }) ``` -------------------------------- ### Method Override for GET Requests (POST with JSON Body) Source: https://github.com/payloadcms/website/blob/main/public/llms-full.txt Supports performing GET requests using the HTTP POST method with a JSON body, specifically for the `findByID` endpoint. The `X-Payload-HTTP-Method-Override` header must be set to `GET`. ```APIDOC ## POST (with Method Override and JSON Body) ### Description This method allows you to send a GET request to the `findByID` endpoint using the POST HTTP method with a JSON body. This is efficient for large payloads. Parameters are sent as JSON. ### Method POST ### Endpoint `/${collectionSlug}/${id}` ### Headers - **X-Payload-HTTP-Method-Override** (string) - Required - Set to `GET`. - **Content-Type** (string) - Required - Set to `application/json`. - **Accept-Language** (string) - Optional - Language preference. ### Request Body (JSON object containing parameters, accessible under a `data` property in the handler) ### Request Example ```ts const res = await fetch(`${api}/${collectionSlug}/${id}`, { // Only the findByID endpoint supports HTTP method overrides with JSON data method: 'POST', credentials: 'include', headers: { 'Accept-Language': i18n.language, 'Content-Type': 'application/json', 'X-Payload-HTTP-Method-Override': 'GET', }, body: JSON.stringify({ depth: 1, locale: 'en', }), }) ``` ### Response #### Success Response (200) (Response body of the equivalent GET request) ``` -------------------------------- ### Basic Hook Setup with Subscribe and Unsubscribe Source: https://github.com/payloadcms/website/blob/main/public/llms-full.txt Use the `subscribe` function to listen for Live Preview events and `unsubscribe` to clean up event listeners. This forms the foundation for custom hooks. ```tsx import { subscribe, unsubscribe } from '@payloadcms/live-preview' // To build your own hook, subscribe to Live Preview events using the `subscribe` function // It handles everything from: // 1. Listening to `window.postMessage` events // 2. Merging initial data with active form state // 3. Populating relationships and uploads // 4. Calling the `onChange` callback with the result // Your hook should also: // 1. Tell the Admin Panel when it is ready to receive messages // 2. Handle the results of the `onChange` callback to update the UI // 3. Unsubscribe from the `window.postMessage` events when it unmounts ``` -------------------------------- ### Sync Community Help and Search Index Source: https://context7.com/payloadcms/website/llms.txt Orchestrates the full community-help sync pipeline. Maximum execution time is 5 minutes. Errors per task are caught and logged without aborting the pipeline. ```bash curl "https://payloadcms.com/api/sync-ch" # → {"success": true} # Tasks run in order: clearDuplicateThreads → fetchDiscord → fetchGitHub → syncToAlgolia # Errors per task are caught and logged without aborting the pipeline ``` -------------------------------- ### SDK `select` Example Source: https://github.com/payloadcms/website/blob/main/public/llms-full.txt Demonstrates how to use the `select` option with the Payload SDK to retrieve only specific fields from a collection. ```APIDOC ## SDK `select` Example ### Description This example shows how to fetch a post by its ID and only retrieve the `id` field by passing an empty `select` object. ### Method `findByID` ### Parameters - `collection` (string) - The name of the collection to query. - `id` (string) - The ID of the document to retrieve. - `select` ({}) ### Request Example ```ts const post = await payload.findByID({ collection: 'posts', id: '1', select: {}, }) console.log(post) // { id: '1' } ``` ### Response #### Success Response (200) - `id` (string) - The ID of the post. ``` -------------------------------- ### Override GET Request with POST using JSON Data Source: https://github.com/payloadcms/website/blob/main/public/llms-full.txt For supported endpoints, you can override a GET request with POST by sending JSON data in the request body with `Content-Type: application/json`. The `X-Payload-HTTP-Method-Override` header must still be set to `GET`. ```typescript const res = await fetch(`${api}/${collectionSlug}/${id}`, { // Only the findByID endpoint supports HTTP method overrides with JSON data method: 'POST', credentials: 'include', headers: { 'Accept-Language': i18n.language, 'Content-Type': 'application/json', 'X-Payload-HTTP-Method-Override': 'GET', }, body: JSON.stringify({ depth: 1, locale: 'en', }), }) ``` -------------------------------- ### Scaffold New Payload App with create-payload-app Source: https://github.com/payloadcms/website/blob/main/public/llms-full.txt Use this command to quickly set up a new Payload app. Follow the prompts to complete the setup. ```bash npx create-payload-app ``` -------------------------------- ### Initialize EcommerceProvider Source: https://github.com/payloadcms/website/blob/main/public/llms-full.txt Wrap your application with EcommerceProvider to enable ecommerce context. Configure supported currencies and enable product variants. ```tsx import { EcommerceProvider } from '@payloadcms/plugin-ecommerce/client/react' // Import any payment adapters you want to use on the client side import { stripeAdapterClient } from '@payloadcms/plugin-ecommerce/payments/stripe' import { USD, EUR } from '@payloadcms/plugin-ecommerce' export const Providers = () => ( {children} ) ``` -------------------------------- ### Package.json Scripts for Payload Migrations and Build Source: https://github.com/payloadcms/website/blob/main/public/llms-full.txt Example package.json scripts demonstrating how to integrate Payload migrations into your build process. The 'ci' script runs migrations before building the application, suitable for CI/CD pipelines. ```json "scripts": { // For running in dev mode "dev": "next dev", // To build your Next + Payload app for production "build": "next build", // A "tie-in" to Payload's CLI for convenience // this helps you run `pnpm payload migrate:create` and similar "payload": "cross-env NODE_OPTIONS=--no-deprecation payload", // This command is what you'd set your `build script` to. // Notice how it runs `payload migrate` and then `pnpm build`? // This will run all migrations for you before building, in your CI, // against your production database "ci": "payload migrate && pnpm build" } ``` -------------------------------- ### Build Basic Payload Config Source: https://github.com/payloadcms/website/blob/main/public/llms-full.txt This is a minimal Payload configuration example. It sets up the database adapter and defines a simple 'pages' collection with a 'title' field. Ensure environment variables for secret and database URL are set. ```typescript import { buildConfig } from 'payload' import { mongooseAdapter } from '@payloadcms/db-mongodb' export default buildConfig({ secret: process.env.PAYLOAD_SECRET, db: mongooseAdapter({ url: process.env.DATABASE_URL, }), collections: [ { slug: 'pages', fields: [ { name: 'title', type: 'text', }, ], }, ], }) ``` -------------------------------- ### REST API `select` Example Source: https://github.com/payloadcms/website/blob/main/public/llms-full.txt Illustrates how to use the `select` query parameter in the REST API to specify which fields to include in the response. ```APIDOC ## REST API `select` Example ### Description This example demonstrates how to use the `select` query parameter in the REST API to fetch posts and include specific fields like `color` and nested fields within `group`. ### Method GET ### Endpoint `/api/posts?select[color]=true&select[group][number]=true` ### Query Parameters - `select[color]` (boolean) - Required - Whether to include the `color` field. - `select[group][number]` (boolean) - Required - Whether to include the nested `number` field within the `group` object. ### Request Example ```ts fetch( 'https://localhost:3000/api/posts?select[color]=true&select[group][number]=true' ) .then((res) => res.json()) .then((data) => console.log(data)) ``` ### Response #### Success Response (200) - Fields specified in the `select` query parameter will be included. ``` -------------------------------- ### Install Redirects Plugin Source: https://github.com/payloadcms/website/blob/main/public/llms-full.txt Install the @payloadcms/plugin-redirects package using a JavaScript package manager like pnpm, npm, or Yarn. ```bash pnpm add @payloadcms/plugin-redirects ``` -------------------------------- ### Install Vercel Blob Storage Adapter Source: https://github.com/payloadcms/website/blob/main/public/llms-full.txt Install the Vercel Blob storage adapter for Payload CMS using pnpm. ```sh pnpm add @payloadcms/storage-vercel-blob ``` -------------------------------- ### Create a New Payload App (Blank Template) Source: https://github.com/payloadcms/website/blob/main/public/llms-full.txt Use this command to scaffold a new Payload application from a blank template. This is a good starting point for custom enterprise tools. ```bash npx create-payload-app@latest -t blank ``` -------------------------------- ### Create a Client Feature with Plugins Source: https://github.com/payloadcms/website/blob/main/public/llms-full.txt Demonstrates how to create a client feature for the Lexical editor and include custom plugins. ```typescript 'use client' import { createClientFeature } from '@payloadcms/richtext-lexical/client' import { MyPlugin } from './plugin' export const MyClientFeature = createClientFeature({ plugins: [MyPlugin], }) ``` -------------------------------- ### SDK Initialization with Custom Fetch Source: https://github.com/payloadcms/website/blob/main/public/llms-full.txt Initializes the Payload SDK with custom fetch implementation and base initialization options. ```APIDOC ## SDK Initialization with Custom Fetch ### Description Initializes the Payload SDK with custom fetch implementation and base initialization options. ### Method `new PayloadSDK(config)` ### Parameters #### Configuration Options - **baseInit** (object) - Optional - Base `RequestInit` properties to be merged with requests. - **credentials** (string) - Optional - Specifies whether credentials should be sent with the request ('include', 'same-origin', 'omit'). - **baseURL** (string) - Optional - The base URL for API requests. - **fetch** (function) - Optional - A custom fetch function to handle requests. ### Request Example ```javascript const sdk = new PayloadSDK({ baseInit: { credentials: 'include' }, baseURL: 'https://example.com/api', fetch: async (url, init) => { console.log('before req') const response = await fetch(url, init) console.log('after req') return response }, }) ``` ``` -------------------------------- ### Checking Plugin Installation via Config Source: https://github.com/payloadcms/website/blob/main/public/llms-full.txt Shows how to check if a specific plugin is installed by iterating through the config's plugins array. ```typescript const hasSeo = config.plugins?.some((p) => p.slug === 'plugin-seo') ?? false ``` -------------------------------- ### Count Documents in a Collection Source: https://github.com/payloadcms/website/blob/main/public/llms-full.txt Use the GET /api/{collection-slug}/count endpoint to get the total number of documents within a collection. ```javascript { operation: "Count", method: "GET", path: "/api/{collection-slug}/count", description: "Count the documents", example: { slug: "count", req: true, res: { totalDocs: 10 }, }, } ``` -------------------------------- ### Initialize Payload REST API SDK Source: https://github.com/payloadcms/website/blob/main/public/llms-full.txt Install the SDK using `pnpm add @payloadcms/sdk`. Initialize the SDK with your API's base URL. This provides a type-safe way to interact with the Payload REST API. ```bash pnpm add @payloadcms/sdk ``` ```typescript import { PayloadSDK } from '@payloadcms/sdk' const sdk = new PayloadSDK({ baseURL: 'https://example.com/api', }) ``` -------------------------------- ### Configure Live Preview in Payload Config Source: https://github.com/payloadcms/website/blob/main/public/llms-full.txt Set up Live Preview globally by defining the `livePreview` property in your root Payload configuration. Specify the URL of your front-end application and the collections to enable it on. ```typescript import { buildConfig } from 'payload' const config = buildConfig({ // ... admin: { // ... livePreview: { url: 'http://localhost:3000', collections: ['pages'], }, }, }) ``` -------------------------------- ### Install Payload Ecommerce Plugin Source: https://github.com/payloadcms/website/blob/main/public/llms-full.txt Install the Payload Ecommerce plugin using pnpm, npm, or Yarn to add e-commerce functionality to your application. ```bash pnpm add @payloadcms/plugin-ecommerce ``` -------------------------------- ### Basic Payload Config Setup Source: https://github.com/payloadcms/website/blob/main/public/llms-full.txt This is the most basic Payload configuration. Import `buildConfig` and export the result of calling it with your configuration object. ```typescript import { buildConfig } from 'payload' export default buildConfig({ // Your config goes here }) ``` -------------------------------- ### Stripe Client-Side Initialization Source: https://github.com/payloadcms/website/blob/main/public/llms-full.txt Initialize the Stripe adapter on the client side using the publishable key for payment handling. ```APIDOC ## Stripe Client-Side Initialization ### Description On the client side, you can use the `publishableKey` to initialize Stripe and handle payments. The client side version of the adapter only requires the `label` and `publishableKey` arguments. Never expose the `secretKey` or `webhookSecret` keys on the client side. ### Arguments #### Required Arguments - **publishableKey** (string) - Required - Your Stripe publishable key. ### Request Example ```ts import { stripeAdapterClient } from '@payloadcms/plugin-ecommerce/payments/stripe' {children} ``` ``` -------------------------------- ### Install Payload TypeScript Plugin Source: https://github.com/payloadcms/website/blob/main/public/llms-full.txt Command to install the experimental Payload TypeScript Language Service Plugin as a development dependency using pnpm. ```bash pnpm add -D @payloadcms/typescript-plugin ``` -------------------------------- ### Live Preview Utility Functions Source: https://github.com/payloadcms/website/blob/main/public/llms-full.txt Utilize `ready` to signal readiness to the Admin Panel and `isDocumentEvent` to filter incoming messages. These are key for building custom live preview integrations. ```typescript import { ready, isDocumentEvent } from '@payloadcms/live-preview' // To build your own component: // 1. Listen for document-level `window.postMessage` events sent from the Admin Panel // 2. Tell the Admin Panel when it is ready to receive messages // 3. Refresh the route every time a new document-level event is received // 4. Unsubscribe from the `window.postMessage` events when it unmounts ``` -------------------------------- ### Install Payload GraphQL CLI Source: https://github.com/payloadcms/website/blob/main/public/llms-full.txt Install the Payload GraphQL package as a dev dependency using pnpm to enable schema generation commands. ```bash pnpm add @payloadcms/graphql -D ``` -------------------------------- ### Implement a Custom React Context Provider Source: https://github.com/payloadcms/website/blob/main/public/llms-full.txt Example of a custom React Context provider. Ensure it includes the `use client` directive and exports a custom hook for accessing the context. ```tsx 'use client' import React, { createContext, use } from 'react' const MyCustomContext = React.createContext(myCustomValue) export function MyProvider({ children }: { children: React.ReactNode }) { return {children} } export const useMyCustomContext = () => use(MyCustomContext) ```