Skip to content

req.user is null in afterRead field hook after user is signed in #11786

Open
@Talaween

Description

@Talaween

Describe the Bug

I have the following field in a posts collection to save the user favourite posts, I have added an afterRead hook to return only the current user if the user favourite the posts otherwise it should return an empty array.

however, req.user is always returning null even for logged in users, therefore this logic fails

{
      name: 'favedBy',
      type: 'relationship',
      relationTo: 'users',
      hasMany: true,
      admin: {
        description: 'Users who have favorited this tool',
      },
      hooks: {
        afterRead: [
          async ({ value, req }) => {
            if (req.user?.roles?.includes('super-admin')) {
              return value
            }
            console.log('user:', req.user) //always print 'null' even when user is logged in

            return value?.filter((id: string) => id === req.user?.id) //this logic will not work as user is always null
          },
        ],
      },
    },

Link to the code that reproduces this issue

https://github.com/Talaween/payload/tree/main

Reproduction Steps

  • run pnpm dev _community
  • in broswer navigate to localhost:3000/admin
  • in the terminal, the console statement prints null for the user value even though the user is logged in

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

area: core

Environment Info

Binaries:
  Node: 23.8.0
  npm: N/A
  Yarn: N/A
  pnpm: N/A
Relevant Packages:
  payload: 3.28.1
  next: 15.2.2
  @payloadcms/db-mongodb: 3.28.1
  @payloadcms/email-nodemailer: 3.28.1
  @payloadcms/graphql: 3.28.1
  @payloadcms/next/utilities: 3.28.1
  @payloadcms/payload-cloud: 3.28.1
  @payloadcms/richtext-lexical: 3.28.1
  @payloadcms/translations: 3.28.1
  @payloadcms/ui/shared: 3.28.1
  react: 19.0.0
  react-dom: 19.0.0
Operating System:
  Platform: win32
  Arch: x64
  Version: Windows 11 Home
  Available memory (MB): 65274
  Available CPU cores: 32

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions