Hi all,
I've really been enjoying building with Payload 3.0 the past few months and am excited about making it a core part of my web agency's tech stack, but have recently run into an issue when trying to configure Live Preview for the first time.
I've been using the Local API to populate all my routes in the Next App Router, but once I got drafts working for live preview, I realized that I had overlooked the
overrideAccessflag and was not conforming to the access rules I had set up for drafts to be restricted to admin users.
This led me to a broader issue when I tried to find a way to provide the correct user scope to the Local API and realized that the JWT token is insufficient for that field - leading me to the following (anti-)pattern:
const cookieStore = cookies()
const token = cookieStore.get('payload-token')
const userRes = await fetch(process.env.NEXT_PUBLIC_SERVER_URL + '/api/users/me', {
headers: {
Authorization: `JWT ${token?.value}`,
},
})
const userJson = await userRes.json()
const data = await payload.findGlobal({
draft: true,
slug: 'extras',
depth: 2,
user: userJson?.user,
overrideAccess: false,
pagination: false
})Is it simply not recommended to use the Local API versus the REST API for access-restricted tasks or is there a better pattern for storing/accessing user data to be used with the Local API that ideally doesn't require a separate round trip to the server?
Thank you for the help!
Where exactly is this code being executed? If its in some custom Next.js route then Payload has no knowledge of what is happening and you need to handle the authentication yourself.
I had a similar usecase where I had to perform a
fetchand authenticate it myself to download a private file.
There is the
payload.login()that can help you login with user/pass/apiKey and
payload.auth()which takes in
headersor a
reqto give you a
AuthResult. Both are better than doing a
fetchto
/api/users/me.
However, I think what you might want is a custom endpoint:
With custom endpoints the request arrives with the headers and a
payloadobject you can use which will respect
Access Controlsfor free. It should be a good fit for your issue.
Thank you for your response
@356003102169759755! The payload.auth() call was exactly what I was looking for, but that is certainly helpful information about the custom endpoints to keep in mind as well!
Star
Discord
online
Get dedicated engineering support directly from the Payload team.