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-apiSo 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.ts2. Modify server.ts to use the getPayload method instead of default initialization (look at line 18)
3. Same with server.default.ts (line 20)
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
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
Discord
online
Get dedicated engineering support directly from the Payload team.