Skip to content

Local API mutates the passed req: nested call with a different locale changes req.locale of the outer operation #18844

Open

Description

@SuperNiceDev

Describe the Bug

Passing req to a Local API call, as recommended for transactions, mutates that req object. createLocalReq writes locale, fallbackLocale and, if depth is given, query.depth straight onto the request object it receives:

// packages/payload/src/utilities/createLocalReq.ts
req.locale = localeCandidate && typeof localeCandidate === 'string' ? localeCandidate : defaultLocale
req.fallbackLocale = sanitizedFallback
if (typeof depth !== 'undefined') req.query.depth = depth

Example:

  • A field hook on an en save reads a sibling value in the default locale.
  • After that nested call, req.locale is 'de' for the rest of the hook.
  • Every later hook in the same operation shares that req object, so they all see 'de' too, as does any code that branches on req.locale.
  • req.fallbackLocale and req.query.depth change the same way.

This fails silently. In our case, a beforeValidate hook adds an /en prefix to a localized slug based on req.locale. It stored the en slug without the prefix, because the nested read had switched req.locale to de.

Expected: a nested Local API call does not change the locale, fallback locale or depth of the operation that called it. For example, createLocalReq could scope these values to the nested operation instead of writing them onto the shared object. Alternatively, the docs on passing req should warn about this.

Link to the code that reproduces this issue

localization: { locales: ['en', 'de'], defaultLocale: 'de' },
collections: [
  {
    slug: 'pages',
    fields: [
      {
        name: 'slug',
        type: 'text',
        localized: true,
        hooks: {
          beforeValidate: [
            async ({ originalDoc, req, value }) => {
              console.log('before', req.locale) // 'en'
              await req.payload.findByID({
                collection: 'pages',
                id: originalDoc.id,
                locale: 'de',
                depth: 0,
                req,
              })
              console.log('after', req.locale) // 'de'
              return value
            },
          ],
        },
      },
    ],
  },
],

Link to the code that reproduces this issue

none

Reproduction Steps

  1. Create a pages document in de.
  2. Run payload.update({ collection: 'pages', id, locale: 'en', data: { slug: 'x' } }), or save the document in en in the admin.
  3. The hook logs before en and then after de. req.locale stays de for the rest of the operation.

Workaround: use req.payload.db.findOne({ collection, where, locale, req }), which keeps the transaction but does not go through createLocalReq. Alternatively, save and restore req.locale / req.fallbackLocale around the call.

Which area(s) are affected?

area: core (Local API, hooks, localization)

Environment Info

Binaries:
  Node: 22.22.2
  npm: 10.9.7
  Yarn: 1.22.19
  pnpm: 10.28.2
Relevant Packages:
  payload: 3.90.2
  @payloadcms/db-postgres: 3.90.2
  next: 16.4.0
  react: 19.3.0
Operating System:
  Platform: darwin
  Arch: arm64

Which area(s) are affected?

Not sure

Environment Info

...

Activity

  1. added
    status: needs-triage
    validate-reproduction
    on Oct 20, 2026
  2. added and removed
    validate-reproduction
    on Oct 20, 2026
  3. github-actions commented on Oct 20, 2026

    @github-actions
    Contributor

    Please add a reproduction in order for us to be able to investigate.

    Depending on the quality of reproduction steps, this issue may be closed if no reproduction is provided.

    Why was this issue marked with the invalid-reproduction label?

    To be able to investigate, we need access to a reproduction to identify what triggered the issue. We prefer a link to a public GitHub repository created with create-payload-app@latest -t blank or a forked/branched version of this repository with tests added (more info in the reproduction-guide).

    To make sure the issue is resolved as quickly as possible, please make sure that the reproduction is as minimal as possible. This means that you should remove unnecessary code, files, and dependencies that do not contribute to the issue. Ensure your reproduction does not depend on secrets, 3rd party registries, private dependencies, or any other data that cannot be made public. Avoid a reproduction including a whole monorepo (unless relevant to the issue). The easier it is to reproduce the issue, the quicker we can help.

    Please test your reproduction against the latest version of Payload to make sure your issue has not already been fixed.

    I added a link, why was it still marked?

    Ensure the link is pointing to a codebase that is accessible (e.g. not a private repository). "example.com", "n/a", "will add later", etc. are not acceptable links -- we need to see a public codebase. See the above section for accepted links.

    Useful Resources

  4. faresrafat3 commented on Oct 20, 2026

    @faresrafat3

    Reproduction, in the form the issue asks for: a fork of this repository with the tests added.

    Branch: https://github.com/faresrafat3/payload/tree/isnad/0010-payload-local-req-mutation

    The test lives in the repository's own spec file, packages/payload/src/utilities/createPayloadRequest.spec.ts, in a new describe block. The first two cases fail on the base commit and pass with the change; the third one is there to prove that the inheritance rule is untouched.

    • should not write the operation locale, fallbackLocale or query depth onto the passed-in req — the caller's request keeps its own locale, fallbackLocale and query, while the nested operation still gets what it asked for.
    • should not leak the operation values onto a caller req that has none of them — a caller request that has no locale does not gain one.
    • should still inherit the caller locale when the nested call passes none — unchanged behaviour.

    Measured on this branch's base (c2c9143de8b0), with the new spec in the tree:

    $ node_modules/.bin/vitest run --project unit packages/payload/src/utilities/createPayloadRequest.spec.ts
     Test Files  1 failed (1)
          Tests  2 failed | 7 passed (9)
    

    The two failures are the two leak cases, and the assertion that fails is the leak itself: expect(Object.hasOwn(callerReq, 'locale')).toBe(false) — on the base, the caller's object does have the operation's locale.

    With the change:

    $ node_modules/.bin/vitest run --project unit packages/payload/src/utilities/createPayloadRequest.spec.ts
     Test Files  1 passed (1)
          Tests  13 passed (13)
    

    One note on the code named in the issue: it points at packages/payload/src/utilities/createLocalReq.ts, which is the v3 name. On main the function is createPayloadRequest, and it writes the same three properties onto the request it receives (req.locale = …, req.fallbackLocale = …, req.query.depth = …). This branch is based on main; the same defect is on 3.x under the old name, so a backport is needed there as well.

    What this branch does not do: it does not run the issue's end-to-end scenario — a field hook that reads a sibling value in the default locale and then sees req.locale changed by a nested findByID. The evidence here is unit-level: the spec calls createPayloadRequest with a mock payload, with no database and no hook.

    That end-to-end case is worth writing as an integration test. It is also how a first version of this change was caught: two tests in packages/payload/src/admin/initAdminContext.spec.ts failed with it, because that file exercises the real path, and the cause turned out to be that a request view which mints a new function on every read is never equal to the plain object it stands for.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Buginvalid-reproductionstatus: needs-triagev3

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions