Skip to content

fix(templates): guard realpath() in with-cloudflare-d1 isCLI check#16645

Open
nickhaubner wants to merge 1 commit into
payloadcms:mainfrom
nickhaubner:fix/with-cloudflare-d1-realpath-undefined
Open

fix(templates): guard realpath() in with-cloudflare-d1 isCLI check#16645
nickhaubner wants to merge 1 commit into
payloadcms:mainfrom
nickhaubner:fix/with-cloudflare-d1-realpath-undefined

Conversation

@nickhaubner
Copy link
Copy Markdown

What

One-character fix in `templates/with-cloudflare-d1/src/payload.config.ts` — add optional chaining to the `realpath()` return value before calling `.endsWith()`:

```diff
-const isCLI = process.argv.some((value) => realpath(value).endsWith(path.join('payload', 'bin.js')))
+const isCLI = process.argv.some((value) => realpath(value)?.endsWith(path.join('payload', 'bin.js')))
```

When the bug surfaces

When the template is deployed unmodified to a Cloudflare Worker and any request hits the Next.js handler (e.g. `GET /admin`):

```
TypeError: Cannot read properties of undefined (reading 'endsWith')
```

Every request returns HTTP 500 with the default Next.js error page; the error is not surfaced in Workers Observability, only in `wrangler tail`.

Root cause

`realpath` is defined as `(value) => fs.existsSync(value) ? fs.realpathSync(value) : undefined` — so it returns `undefined` for paths that don't exist on the FS. On Workers, `process.argv` entries (e.g. `'node'`) don't resolve to real files, so `realpath(value)` is `undefined` and the subsequent `.endsWith()` throws. Locally (in `pnpm dev`) and during `payload migrate` this works because there is a real Node binary at `process.argv[0]`.

Test

After applying this patch to the unmodified template and deploying to Workers, `/admin` returns 200 and the "Create First User" form renders correctly. Reproduced and verified on a fresh degit of `templates/with-cloudflare-d1` at d6b2d73, Wrangler 4.61.1, Workers compat date 2026-05-16, Node 24.

The patched config has been running in production at https://cms.sutraelements.com/admin (private downstream repo at https://github.com/nickhaubner/sutraelements; the fix in our local copy lives in src/payload.config.ts#L18).

Risk

Negligible — optional chaining only changes behavior when `realpath()` returns undefined, in which case the previous code would have thrown. All existing successful paths are unchanged.

…heck

On Cloudflare Workers, process.argv entries don't correspond to real files,
so realpath() returns undefined and the subsequent .endsWith() call throws a
TypeError on every request. Add optional chaining to skip non-existent paths
when detecting the payload CLI.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant