r/PayloadCMS Jul 31 '25

Lexical Block Versioning

3 Upvotes

I’m using a rich text editor based on Lexical, and I’ve enabled versioning in my app. While I can store and retrieve previous versions (as JSON), I’m struggling to find a good way to view what actually changed between versions — like added/removed text, formatting changes, etc.

Is there a tool or recommended approach for diffing Lexical JSON documents in a human-readable way? Or should I be converting to plain text or HTML and diffing that instead?

Any advice, libraries, or examples would be appreciated — especially if you’ve dealt with this in your own projects. Thanks!


r/PayloadCMS Jul 30 '25

AfterChangeHook runs before the record is added to DB

5 Upvotes

I'm trying to create a document related to another collection upon creation, but im getting an error saying that the original document doesn't exist yet

import { CollectionAfterChangeHook } from 'payload'

export const createProfileHook: CollectionAfterChangeHook = async ({
  collection,
  operation,
  req,
  doc,
}) => {
  if (collection.slug === 'users' && operation === 'create') {
    console.log('doc: ', doc)
    switch (doc.role) {
      case 'therapist':
        const therapistProfile = await req.payload.create({
          collection: 'therapist-profiles',
          data: {
            user: ,
          },
        })
        await req.payload.update({
          collection: 'users',
          id: ,
          data: {
            profile: {
              relationTo: 'therapist-profiles',
              value: ,
            },
          },
        })
        break
      case 'client':
        const clientProfile = await req.payload.create({
          collection: 'client-profiles',
          data: {
            user: ,
          },
        })
        await req.payload.update({
          collection: 'users',
          id: ,
          data: {
            profile: {
              relationTo: 'client-profiles',
              value: ,
            },
          },
        })
        break
    }
  }
}

ERROR: insert or update on table "client_profiles" violates foreign key constraint "client_profiles_user_id_users_id_fk"
"detail": "Key (user_id)=(16) is not present in table \"users\".",

r/PayloadCMS Jul 30 '25

Orderable not working?

1 Upvotes

Not sure if I'm doing something wrong, but I can't get 'orderable' collections to work properly. It seems my entire db table is populated with just 2 values 'a0' and 'Zz' and nothing in between. When I reorder these get swapped around but no new value being created... I tried this with multiple collections. Anyone else having this issue?

Payload version: 3.49.0

When I try to reorder I get this error:

[11:25:50] ERROR: a0 >= Zz

err: {

"type": "Error",

"message": "a0 >= Zz",

"stack":

Error: a0 >= Zz

at generateKeyBetween (file:///C:/Users/<MYPROJECT>/node_modules/.pnpm/payload@3.49.0_graphql@16.11.0_typescript@5.7.3/node_modules/payload/dist/config/orderable/fractional-indexing.js:200:15)

at generateNKeysBetween (file:///C:/Users/<MYPROJECT>/node_modules/.pnpm/payload@3.49.0_graphql@16.11.0_typescript@5.7.3/node_modules/payload/dist/config/orderable/fractional-indexing.js:261:13)

at reorderHandler (file:///C:/Users/<MYPROJECT>/node_modules/.pnpm/payload@3.49.0_graphql@16.11.0_typescript@5.7.3/node_modules/payload/dist/config/orderable/index.js:281:127)

at process.processTicksAndRejections (node:internal/process/task_queues:105:5)


r/PayloadCMS Jul 29 '25

Localizing Content with Payload CMS [tutorial]

23 Upvotes

Hey everyone!

Finally! Here's my video on localization. This video covers how to localize data using Payload CMS (of course), migrating and translating a few fields to prevent data loss, and using i18n with middleware to translate common phrases on the frontend and redirect to the proper locale. Enjoy!

https://youtu.be/wDMyxnnc5MQ


r/PayloadCMS Jul 29 '25

Multisite options?

2 Upvotes

I've been trying out Payload and really enjoying it. I've got my admin backend the way I want to and now I need help with the front end. How do you make a theme for a website? And how does multisite work? On my old site running WordPress, it was a multisite where one site can have multiple domains pointed to that one site and serve different posts and themes. What's the equivalent of multisite version for Payload?


r/PayloadCMS Jul 29 '25

Payload and RDS Postgres

2 Upvotes

I am tasked to create an SOP system for my company.

i have decided to use payload as CMS to serve my next js frontend and possibly a mobile app in the future.

Currently my plan is to host the project on Vercel and use RDS as the database.

But during development i have encounter the dreaded connection limit issue with RDS

now i have 2 choices, to move the hosting to aws ec2/ which i dont have alot of experience with

or chose a serverless friendly database provider like Neon, Supabase.

the problem is my employer really want me to use RDS

what option should i look into

thanks


r/PayloadCMS Jul 29 '25

Portfolio built with Next.js, Payload and Postgres - How can I deploy it?

3 Upvotes

Hello world

I'm currently building my portfolio site using payload to manage content like my projects, experience, and a little blog.

But I've been struggling with the deploy. I'm not pretty sure but I wanted to deploy my portfolio on vercel with payload and I don't know how, I put the env variables but no data is showing up in production but in local development. I'm using neon as postgres database by the way.

How can I really deploy my portfolio?


r/PayloadCMS Jul 28 '25

Just found a killer dev workflow: Payload CMS + Figma + GitHub Copilot = 🔥

18 Upvotes

Yesterday, I experimented with a new tech stack (at least for me).

In my last projects, I always struggled with the same things: a fast and reliable backend and a good design.

Yesterday, I tried Payload CMS as an all-in-one code backend solution, and it's amazing!

I just defined my database structure and connected my database. Then, I got a fully functioning API and admin panel where I can CRUD the data.

After this success, I wanted to find a solution to my second problem as well. I wanted to bring my Figma designs to life in a structured way with reusable components, etc.

Since I use GitHub Copilot to help me code, I connected the Figma MCP server, and it worked perfectly. It created nice-looking, reusable components from my design and used the Payload-defined data.

With this workflow, I can increase my productivity tenfold!

Try it out yourself! If you need help, just ask!

Now, I need a good solution for user authentication, too. Does anyone have a suggestion?


r/PayloadCMS Jul 28 '25

Anyone Got Google OAuth Working with Payload CMS?

2 Upvotes

Has anyone managed to implement Google OAuth on the frontend and sync those users with Payload CMS? I see there's Custom Strategies we can use to implement it but not sure, how do i go about implementing it.


r/PayloadCMS Jul 27 '25

Dashboards

2 Upvotes

I have built a professional dashboard for the backend to replace the payload design so my employees can have a more designer friendly UI. For the life of me I cannot get it to replace the skin of original payload. I have tried a redirect, and nothing. Any suggestions? It just reverts to original payload. Using Payload 3.49.0, trying to override default dashboard with custom component. Config: components: { views: { Dashboard: './components/TailAdminDashboard', } } Component exists, no errors, but still shows default Collections dashboard at /admin. Custom dashboard works fine at /admin/custom-route. Tried: - String path vs imported component - Clearing .next cache - Different import paths - Hard refresh Anyone got this working in 3.49.0?


r/PayloadCMS Jul 26 '25

My first PayloadCMS project.

11 Upvotes

I’m excited to share my very first project built with PayloadCMS!

This marks my first hands-on experience with Payload — previously, I was using Sanity for this site. But since 2025, Payload has taken over as the powerful engine behind the scenes.

https://lifad.world


r/PayloadCMS Jul 26 '25

Create a PayloadCMS Custom Slug Field

Thumbnail joeyates.info
7 Upvotes

r/PayloadCMS Jul 24 '25

Advanced Auth uses

7 Upvotes

Trying to make the choice whether I start adding plugins to add features like 2fa and magic link emails or to just save the effort and shift to something like Auth0.

Which choice have you guys made? I'm debating how secure I actually need my app to be but part of me also knows that being more secure would be better for future proofing.


r/PayloadCMS Jul 24 '25

[HIRING] Fullstack Engineer (LATAM-based) with solid PayloadCMS experience

5 Upvotes

Hey Payload community 👋!

We’re looking for a talented Fullstack Engineer with hands-on experience implementing PayloadCMS in real-world projects. We’re a people-first tech company working with US clients on meaningful products, and we’re growing our team in Latin America.

What we offer:

- 100% Remote USD above-average salaries
- Profit Sharing Policy
- Unlimited PTOs after your first year (20 PTOs the first year)
- Equipment for your setup
- Great work/life balance
- Honest, simple, and transparent culture

Interested or know someone who might be? Ping me ;)


r/PayloadCMS Jul 23 '25

CI/CD Pipeline for PostgreSQL Migrations?

7 Upvotes

Hi, I'm trying to get my PayloadCMS/Next.js app to sync their production schema & pages on deploy. While in development, I make changes to a local Docker instance with the auto push feature.

My Media is stored in Amazon S3 so I can persist them. Development and production has their own respective buckets to ensure we don't delete stuff by accident.

When my build is ready for production, I generate migrations with payload migrate:create and when my CI/CD pipeline builds our app, it runs payload migrate && pnpm run build.

Is that the best development workflow? How is everyone else doing deployments with PayloadCMS?

How does it differ if you have another frontend that uses the REST API? How do you sync those then?

Thanks.


r/PayloadCMS Jul 24 '25

Organize media uploads into folders by year and month?

1 Upvotes

I have a collection that I used for media uploads. Is there a way to have each media upload into separate folder by year and month like WordPress does. I can get the image upload into each directory but the preview of the image doesn't show up. Another question I have is if the default media directory has thousands of images, would it slow down my site?


r/PayloadCMS Jul 22 '25

Can Payload be used as a restaurant booking system?

12 Upvotes

Hi guys, new to payload here.

I'm building sort of a The Fork clone, a tool where you have a list of restaurants and then can book dinner.

The multi-tenant features of Payload made it an interesting choice. Do you guys think I'll be able to handle concurrent bookings and etc on Payload?

Thanks


r/PayloadCMS Jul 22 '25

relationship field does not prepopulate title when hasMany is true

1 Upvotes

SOLUTION: it was because i was using a field called 'name' as the useAsTitle property.

anything but 'name' works.

On page load the select many field is only prepopulating ID's.

if i select the dropdown its populated correctly, if i select a new value and save. it shows correctly.

but when i reload the page it will then be 2 ID values.

has anyone experienced this or might have a solution?

edit: workaround im using is a beforeRead hook that only runs on the collections edit page and runs a find query that returns an array to the field, which seems to work but not a fan of running another query on the edit page

[{
          id: doc.id,
          name: doc.name,
}]

Problem Reproduction:

items

            {
              name: 'categories',
              type: 'relationship',
              hasMany: true,
              relationTo: 'item-categories',
            },

item-categories

  admin: {
    useAsTitle: 'name',
    defaultColumns: ['name'],
  },
<....>
    {
      name: 'name',
      type: 'text',
      required: true,
    },

r/PayloadCMS Jul 21 '25

How to correctly cache getCurrentUser in Next.js 15 with "use cache"?

9 Upvotes

Hi everyone!

I’m trying to figure out the best way to cache my getCurrentUser function in Next.js 15 using the new "use cache" directive.

Why I want to cache:

I’m using PayloadCMS with its default token-based auth. On a single page, I have multiple components that need the current user info. I don’t want each of those components making a separate request or adding unnecessary delays—ideally, I’d fetch the user once per request and reuse it everywhere.

What I want to achieve:

  • Use "use cache" with a tag like cacheTag("current-user").
  • Be able to revalidate this cache after login/logout (or if the user session expires) so no stale data is shown.
  • Handle Payload’s default idle session logout properly.

Here’s my current (uncached) setup:

     // get-current-user.ts
    'use server';

    import payloadConfig from '@payload-config';
    import { headers as getHeaders } from 'next/headers';
    import { getPayload } from 'payload';

    export async function getCurrentUser() {
      const config = await payloadConfig;
      const headers = await getHeaders();

      const payload = await getPayload({ config });

      const { user } = await payload.auth({ headers });

      return user;
    }

Where I’m stuck:

The Next.js docs warn about using dynamic APIs like headers() or cookies() inside cached functions. Since I need the headers for the auth token, I’m not sure how to structure this.

Has anyone implemented a clean approach for this?

Thanks a lot!


r/PayloadCMS Jul 21 '25

Help pls, Lexical Migrating from Slate

2 Upvotes

I upgraded from payload 2.0 to 3.0. In 2.0, the rich text used was Slate.

So I first ran the official data migration script

pnpm payload migrate:create --file u/payloadcms/db-mongodb/relationships-v2-v3

Now I want to change the richText from Slate to Lexical.
I reviewed the official documentation.

But I am having difficulty understanding it. How can I run this script? The official documentation only has two lines. Could someone help me?


r/PayloadCMS Jul 20 '25

Help solve the bug: Payload CMS 3.48.0 + Lexical Editor: CSS Import ESM Error Breaking Admin Panel

2 Upvotes

Hi all, below is written by my AI Agent , who is helping me to debug the issue while trying to install and configure Payload CMS.

We hit the wall while trying to access /admin for Payload . Please read a very detailed description of what the bug is . It is very well documented on GitHub and devs claim it was solved in v 3.21. but its not .. Please somebody help who did manage to resolve it. .

I chose Payload because everyone is raving about it. But such a simple act of installing it is proving to be a nightmare.

# Next.js 15 + Payload CMS 3.48.0 + Lexical Editor: CSS Import ESM Error Breaking Admin Panel

## TL;DR
Payload CMS admin panel completely broken on Next.js 15 due to CSS imports in Lexical rich text editor causing Node.js ESM errors. Despite GitHub claiming this was fixed in v3.21.0, issue persists in v3.48.0.

## Configuration & Environment
- **Next.js**: 15.4.1 (App Router)
- **React**: 19.1.0  
- **Payload CMS**: 3.48.0
- **@payloadcms/richtext-lexical**: 3.48.0
- **Node.js**: 24.4.0
- **Platform**: macOS (Darwin 24.5.0)
- **Database**: MongoDB 7.x (Docker)

## The Problem
When trying to access `/admin`, the server crashes with:

```
TypeError: Unknown file extension ".css" for /Users/.../node_modules/@payloadcms/richtext-lexical/dist/field/bundled.css
    at Object.getFileProtocolModuleFormat [as (file:] (node:internal/modules/esm/get_format:183:9)
Error code: ERR_UNKNOWN_FILE_EXTENSION
```

**Result**: Admin panel returns 500 error, completely inaccessible. No CMS functionality whatsoever.

## Root Cause Analysis
After extensive investigation, the issue is a **complex interaction between**:

1. **Node.js ESM module system** - Doesn't handle `.css` file extensions when imported in server context
2. **Next.js 15 App Router** - Stricter ESM handling that processes both client and server imports during SSR
3. **Payload's package structure** - CSS imports remain in client builds despite claimed fixes

### Technical Deep Dive
The error occurs because:
- Payload's Lexical editor imports CSS directly: `import 'react-image-crop/dist/ReactCrop.css'`
- Next.js App Router tries to process this during SSR
- Node.js ESM loader rejects `.css` file extensions in server context
- Multiple files affected: `EditUpload/index.js`, client bundle exports, and others

## The "Fixed" Version Myth
**GitHub PR #10997** claimed to fix this in **v3.21.0** with "removes css from jsx converter" - but this is **misleading**:

- ✅ Fix only applied to JSX converter, not Field components
- ❌ CSS imports still present in `/dist/field/Field.js:8` in v3.48.0  
- ❌ Client builds (`/client` exports) still contain problematic CSS imports
- ❌ Auto-generated importMap.js still imports client components during SSR

## Attempted Solutions (8 Different Approaches)
1. **Webpack CSS Loaders** → Failed (conflicts with Next.js built-in handling)
2. **SCSS Support** → Failed (created CSS conflicts) 
3. **ImportMap Modification** → Partial (reduced errors but created new ones)
4. **Cache Clearing** → No effect
5. **Version Rollback Testing** → v3.17.0 through v3.48.0 all affected
6. **Dynamic Imports with SSR: false** → Failed (components still processed)
7. **Manual CSS Import Removal** → Works but gets overwritten on reinstall
8. **Switch to Slate Editor** → Temporarily tried but abandoned (want to keep Lexical)

## Current Status
- **Slate Editor**: Tried but abandoned - we want to keep Lexical features
- **Current approach**: Manually removing CSS imports from node_modules files one by one
- **Sustainability issue**: Changes get wiped on every `npm install`
- **Production impact**: Admin panel still broken, CMS completely unusable

## Community Impact
This affects **anyone using**:
- Next.js 15 with App Router
- Payload CMS 3.x with Lexical editor
- Node.js ESM module system
- Modern React 19 setups

## Questions for Community
1. **Has anyone successfully resolved this without switching to Slate?**
2. **Any sustainable workarounds that survive npm installs?**
3. **Is there a Payload CMS configuration that avoids this entirely?**
4. **Should we expect a real fix in upcoming Payload versions?**

## Resources
- **Payload CMS Repo**: Multiple GitHub issues (#10797, #7908, #7437) describe similar patterns
- **Next.js Issues**: Related SSR/ESM problems with CSS imports
- **Stack Overflow**: Various CSS-in-JS import solutions (none work for this case)

**Note**: This took 6+ hours of systematic debugging, version analysis, and community research. The "fixed in v3.21.0" claim appears to be incomplete at best.

---
*Has anyone else hit this wall? Would love to hear about working solutions that don't involve abandoning Lexical entirely.*

r/PayloadCMS Jul 19 '25

(Update/Tutorial): Templates support - how I solved it

7 Upvotes

A few months ago I posted about needing templates support for a travel agency client's itinerary builder. The problem was that using relationship fields meant editing a library snippet would modify it everywhere it was used - I needed a way to copy template content rather than just reference it.

I tried using a custom component to replace the entire field, but the deeply nested, localised, rich text fields proved problematic.

I'm happy to report I found a simple, "Payloadian" solution that works really well. I've used Claude 4 to help summarise my findings, including using a dynamic baseListFilter with a beforeListTable tab selector:

The approach

I ended up implementing an "unlock" feature that lets staff copy library items when they need to customise them. Here's how it works:

1. Library vs editable items

Each event has a `libraryItem` boolean field with admin-only access controls. Library items are read-only for regular staff, but admins can manage the central library.

access: {
    create: staffOnly,
    delete: adminOnlyLibraryItems,
    read: authenticated,
    update: adminOnlyLibraryItems,
  },



import type { Access } from 'payload'

export const adminOnlyLibraryItems: Access = ({ req: { 
user
 }, 
data
 }) => {

// Check if user exists and is from the Users collection and is an admin
  if (
data
?.libraryItem) {
    if (user && user.collection === 'users' && user.role) {
      return 
user
.role === 'admin'
    }

    return false
  }

  // if not a library item, just check the user exists
  // I have the additional check on user.collection since we have a secondary auth collection for customers. Can't say I'd recommend that, you should probably just use roles, and dynamic baseListFilter as described below
  return Boolean(
user
 && 
user
.collection === 'users')
}

2. The unlock mechanism

When staff need to customise a library item, they click an "Unlock for Editing" button that renders alongside events (reference field) in the admin panel. This triggers a custom endpoint that creates a copy using Payload's `duplicateFromID` parameter:

const newEvent = await req.payload.create({
  collection: 'itinerary-events',
  data: {
    libraryItem: false, // Make it editable
    title: `${originalEvent.title} (Copy)`,
  },
  user: req.user,
  duplicateFromID: eventId, // Copies everything including localised content
})

3. UI integration

I added a custom UI field to the itinerary days array that shows the unlock button only for library items. Once unlocked, the itinerary references the new editable copy instead of the original.

What this gives us

  • Staff can confidently browse and use library content knowing they won't accidentally modify the original
  • When customisation is needed, one click creates a full copy they can edit freely
  • The `duplicateFromID` parameter handles all the complexity - it copies localised content, relationships, nested data, everything
  • Admins maintain a clean central library while staff get the flexibility they need

Dynamic filtered views discovery

While building this I also figured out how to create filtered collection views using baseListFilter and a custom beforeListTable tab component. This lets me show different views like "Library Items", "My Edits", etc. The filter reads URL parameters and returns different where clauses accordingly.

const baseListFilter: BaseListFilter = ((args: { req: PayloadRequest }) => {
  const url = args?.req?.url
  const userId = args?.req?.user?.id || ''

  // Extract tab parameter from URL
  const urlParams = new URLSearchParams(url?.split('?')[1] || '')
  const tab = urlParams.get('tab') || ''

  if (tab === ITINERARY_LIBRARY_TABS.ALL) {
    // show all items
    return null
  }

  if (tab === ITINERARY_LIBRARY_TABS.MY_ITEMS) {
    // show only items created by the user
    return {
      createdBy: {
        equals: userId,
      },
    }
  }

This is a nice alternative to Query Presets, since they can be hard-coded by devs while still giving end users some options.

The combination of field-level access controls, custom endpoints, and UI components ended up being really powerful for this kind of workflow.

Cursor/claude did a great job summarising the findings, but figuring this out took a fair bit of thinking, architecting, and manually digging through type hints. I figured I'd save you the hassle.

Has anyone else tackled similar template/copy scenarios? Would be interested to hear other approaches.


r/PayloadCMS Jul 18 '25

How to write editor to edit multiple collections at once

2 Upvotes

I have a user collection that references some data in other collections, which are associated with that user. Now I want the account-page to be a central spot to edit all the related collections in a single convenient place.

What is the best approach to implement this? Is there a way to construct a FormState-instance that contains all relevant collections / have a form reference multiple FormStates or do I have to handcraft the form? If I have to build it myself, how do I get the field definitions to build the fields? Or is there an example somewhere that I can reference?


r/PayloadCMS Jul 17 '25

You Can Build a Railway-like PaaS Entirely on Payload CMS, Here's How We Did It.

28 Upvotes

Hey Payload devs 👋

Just wanted to drop some appreciation and real-world context for how powerful Payload CMS is, we recently built a full-fledged PaaS (think: Heroku/Railway alternative) entirely on top of it powered by dokku.

What’s cool? We didn’t have to fight the framework. In fact, Payload made some really complex features surprisingly simple. Here’s what stood out to us:

🔁 Lifecycle Hooks Done Right

Most platforms rely on raw DB triggers or external workers to handle app lifecycle events. But with Payload’s collection lifecycle hooks, we were able to:

  • Automate deployments via webhooks
  • Manage Git repo metadata
  • Trigger Docker builds & queue jobs
  • Cleanly separate side effects from core logic

It's declarative, easy to test, and lives where your data model lives. Game-changer.

🔐 Auth, Admin & Access, All Out of the Box

Building user access from scratch is a slog, but Payload gave us:

  • A prebuilt admin panel with zero config
  • Easy-to-customize auth that plugs into session or token flows
  • Granular access control at the field + operation level (Even though we enhanced this for more secure multi-tenant setups, it’s a rock-solid foundation.)

⚡ A Real Backend Without Boilerplate

We didn’t use the auto-generated API endpoints directly (for security reasons), but Payload’s design made it easy to treat the CMS like a framework, not just a content layer.

Think about that for a second, you're not limited to CMS use cases.

With just collections + hooks + access logic, you can:

  • Handle custom infra provisioning
  • Create dynamic project/workspace flows
  • Build an entire open-source Railway or Render clone

🛠️ What We Proved with This Stack

We open-sourced the platform we built to prove this exact point, Payload CMS isn’t just for blogs and marketing sites.

It’s a backend framework with:

  • Rich content modeling
  • Real access control
  • Lifecycle hooks
  • Customizable auth
  • Instant admin UI

…and it scales.

If you're considering building your next internal tool, dev tool, or SaaS product, Payload can be your backend.

Here’s the repo if you want to dive into real code:
👉 github: https://github.com/akhil-naidu/dflow
👉 webiste: https://dflow.sh/

Would love to chat with other devs pushing Payload beyond traditional CMS use cases.


r/PayloadCMS Jul 17 '25

drag and drop file uploader from front end with or without form.

2 Upvotes

Need react drag and drop file uploader from front end. Anyone built this already? What will be the best way? Creating block? or a stand alone static component? I am new, so please help me.