payload icon indicating copy to clipboard operation
payload copied to clipboard

Bug: Unexpected `POST` to `/api/users` during file upload in Cloudflare environment causes 'Unauthorized' error

Open heatloss opened this issue 1 year ago • 2 comments

Describe the Bug

When uploading a file to a Media collection in a Payload CMS application deployed to Cloudflare Workers (and previewed with wrangler), the admin UI incorrectly sends a POST request to /api/users. This happens even when a non-admin user with the correct permissions is logged in. The request to /api/users fails with an "Unauthorized" error (as expected, since only admins can create users), which then causes the entire file upload process to fail with a 500 error.

Versions

  • payload: 3.58.0
  • @opennextjs/cloudflare: ^1.9.1
  • @payloadcms/db-d1-sqlite: 3.58.0
  • @payloadcms/storage-r2: 3.58.0
  • wrangler: ~4.42.0

Link to the code that reproduces this issue

https://github.com/heatloss/payload-d1/tree/wasm-image-resizing

Reproduction Steps

  1. Set up a Payload CMS project using Cloudflare D1 for the database and Cloudflare R2 for storage.
  2. Configure a users collection where create access is restricted to admins.
  3. Configure a media collection where create access is granted to a non-admin role (e.g., creator).
  4. Create two users: one admin and one creator.
  5. Log in to the admin UI as the creator user.
  6. Navigate to the media collection and attempt to upload an image.

Expected Behavior

The file upload should succeed. The create access control on the media collection should pass, and the file should be uploaded to R2. There should be no API calls to /api/users.

Actual Behavior

  1. The create access control on the media collection is checked, and the user object is correctly passed to it.
  2. Immediately after, the browser sends a POST request to /api/users.
  3. This request fails with a 500 Internal Server Error wrapping an "Unauthorized" error, because the logged-in creator user does not have permission to create users.
  4. The file upload process fails.

Here are the relevant logs from the wrangler preview, showing the successful access check followed by the failing POST to /api/users:

1 [wrangler:info] GET /admin/collections/media/create 200 OK (30ms) 2 Checking create access for Media. User: { 3 id: '61104b13-126a-4e8d-bc90-d7dcde4fb576', 4 role: 'creator', 5 ... 6 } 7 [wrangler:info] POST /api/users 500 Internal Server Error (5ms) 8 ✘ [ERROR] Error: Unauthorized 9 ...

Relevant Configuration

src/collections/Users.ts:

1 import type { CollectionConfig } from 'payload'
2 
3 export const Users: CollectionConfig = {
4   slug: 'users',
5   auth: true,
6   admin: {
7     useAsTitle: 'email',
8   },
9   access: {

10 create: ({ req: { user } }) => { 11 return user?.role === 'admin' 12 }, 13 // ... other access controls 14 }, 15 fields: [ 16 // ... fields 17 { 18 name: 'role', 19 type: 'select', 20 options: ['admin', 'creator', 'editor', 'reader'], 21 defaultValue: 'reader', 22 required: true, 23 }, 24 ], 25 }

src/collections/Media.ts:

1 import type { CollectionConfig } from 'payload'
2 
3 export const Media: CollectionConfig = {
4   slug: 'media',
5   upload: {
6     staticDir: 'media',
7   },
8   access: {
9     create: ({ req: { user } }) => {

10 return user && ['creator', 'editor', 'admin'].includes(user.role) 11 }, 12 read: () => true, 13 // ... other access controls 14 }, 15 fields: [ 16 // ... fields 17 ], 18 }

Which area(s) are affected? (Select all that apply)

area: core, plugin: cloud, area: ui

Environment Info

Binaries:
  Node: 22.18.0
  npm: 10.9.3
  Yarn: N/A
  pnpm: 10.18.0
Relevant Packages:
  payload: 3.58.0
  next: 15.5.4
  @payloadcms/email-nodemailer: 3.58.0
  @payloadcms/graphql: 3.58.0
  @payloadcms/next/utilities: 3.58.0
  @payloadcms/payload-cloud: 3.58.0
  @payloadcms/plugin-cloud-storage: 3.58.0
  @payloadcms/richtext-lexical: 3.58.0
  @payloadcms/translations: 3.58.0
  @payloadcms/ui/shared: 3.58.0
  react: 19.2.0
  react-dom: 19.2.0
Operating System:
  Platform: darwin
  Arch: arm64
  Version: Darwin Kernel Version 24.6.0: Mon Jul 14 11:30:40 PDT 2025; root:xnu-11417.140.69~1/RELEASE_ARM64_T6041
  Available memory (MB): 65536
  Available CPU cores: 16

heatloss avatar Oct 06 '25 22:10 heatloss

Update: Partial Resolution + Remaining Authentication Issues

✅ Fixed: Page Load Error

We've resolved the initial page-load issue where accessing the Media create/edit page triggered an erroneous POST to /api/users with a 500 error.

Root Cause: The defaultValue on a relationship field (uploadedBy) was causing Payload to validate the relationship during page load.

Fix Applied: // Before (caused page-load POST to /api/users) defaultValue: ({ user }) => user?.id, hooks: { beforeValidate: [ ({ value, req }) => { if (value) return value; return req.user?.id; }, ], }

// After (works correctly) // Removed defaultValue, kept only beforeValidate hook hooks: { beforeValidate: [ ({ value, req }) => { if (value) return value; return req.user?.id; }, ], }

Result: The Media collection page now loads without errors in both local Node.js dev and Cloudflare Workers environments.


❌ Still Broken: Authentication Context Loss in Workers

Two critical issues remain in the Cloudflare Workers environment:

  1. File Upload POST Requests Lose Authentication
  • Symptom: When a user selects a file to upload, req.user becomes undefined during the POST request
  • Error: Unauthorized / 403 Forbidden
  • Environment: Works fine in local Node.js dev (port 3333), fails in Workers (port 8787)
  1. DELETE Requests Lose Authentication
  • Same pattern as file uploads
  • Access control checks show user: undefined
  • Works in Node.js dev, fails in Workers

Debug Output from Workers Preview: Media create access check: { user: undefined, role: undefined } Media create access result: false [wrangler:info] POST /admin/collections/media/create 500 Internal Server Error [POST] http://localhost:8787/api/media?depth=0&fallback-locale=null Media create access check: { user: undefined, role: undefined } Media create access result: false [wrangler:info] POST /api/media 403 Forbidden Error: Unauthorized


Environment Details

  • PayloadCMS: 3.59.1 (updated from 3.59.0, issue persists)
  • OpenNext Cloudflare: 1.9.1
  • Runtime: Cloudflare Workers with local D1 database
  • Working Environment: Node.js dev server (port 3333)
  • Failing Environment: Cloudflare Workers preview (port 8787)

Root Cause Hypothesis

Authentication cookies/sessions are not being properly propagated during:

  • Multipart form data POST requests (file uploads)
  • DELETE requests

This appears to be related to how OpenNext Cloudflare or PayloadCMS handles session persistence in the Workers runtime during non-GET requests. GET requests (page loads) work correctly after our fix, but mutating operations lose the authentication context.

Potentially Related Issues:

  • OpenNext Cloudflare #501: "Multiple Set-Cookie headers are folded in middleware"
  • OpenNext Cloudflare #498: "Multiple cookies are not set properly"
  • PayloadCMS #8052: "Calling an endpoint within another endpoint doesn't preserve req.user"

Questions for Payload Team

  1. Are there known issues with session/cookie handling in Cloudflare Workers for non-GET requests?
  2. Does PayloadCMS have any Workers-specific authentication middleware or configuration we should be using?
  3. Could this be related to how multipart form data is parsed in the Workers runtime?

Any guidance would be greatly appreciated. We're happy to provide additional debug information or test potential fixes.

heatloss avatar Oct 08 '25 21:10 heatloss

Sorry you didn't get a team response on this sooner. Is this still reproducible on the latest v3 version (v3.86.0)? If so, could you confirm your repro steps still apply there and we'll take another look.

JessRynkar avatar Jul 15 '26 16:07 JessRynkar