Simplify your stack and build anything. Or everything.
Build tomorrow’s web with a modern solution you truly own.
Code-based nature means you can build on top of it to power anything.
It’s time to take back your content infrastructure.

Access payload instance in server component (Payload 2)?

default discord avatar
rockybalboa30566 months ago
1

Hi,


is it possible to access payload object instance in a server component? For example:



import payload from 'payload'

export default async function Component() {
  const productsCollection = payload.db.collections['products']
  const product = productsCollection.find(...findQuery...)

  return <>...UI goes here...</>
}


It builds but 'payload' is always udefined here.


Can I do something like that or do I need to have an api endpoint that performs that find operation and then I need to simply fetch the data from that endpoint?



Thanks in advance.



Ok, seems like it is a known issue briefly described here:

https://payloadcms.com/docs/local-api/overview#nextjs-conflict-with-local-api

So there are few steps involved:



1. Look at the example given in that doc and copy the getPayload.ts file into your project:

https://github.com/payloadcms/payload/blob/1.x/examples/custom-server/src/getPayload.ts

2. Modify server.ts to use the getPayload method instead of default initialization (look at line 18)


https://github.com/payloadcms/payload/blob/1.x/examples/custom-server/src/server.ts

3. Same with server.default.ts (line 20)


https://github.com/payloadcms/payload/blob/1.x/examples/custom-server/src/server.default.ts

This basically creates a cached payload instance that can be now accessed anywhere on the server.


So now in your component you can use this new method and do something like this (I'm using the aggregate function to get products but that's of course just my example):



export const ProductsList = async () => {
  const payload = await getPayloadClient()
  const products = await payload.db.collections['products'].aggregate([
    {
      $sort: { createdAt: 1 },
    }
  ])

  return <>...UI rendering products goes here</>
}


Hope this helps.



I'm at 2.18.3 currently

  • default discord avatar
    avemeva7 months ago

    I am also interested in this, currently trying to use

    usePayloadAPI

    , since I haven't figured out how to use the

    payload

    in server component. But using

    usePayloadAPI

    also seems to come with its own challenges.



    What version of payload are u using?

Star on GitHub

Star

Chat on Discord

Discord

online

Can't find what you're looking for?

Get dedicated engineering support directly from the Payload team.