Hello,
I am having some trouble fetching data from Payload, in a NextJS
client component
.
I have no problems fetching my data in
server components
, but in
client components
i am getting a 403 forbidden error.
I have tried useeffect, swr and tanstack query, all with the same result.
The error message reads like this:
{message: 'You are not allowed to perform this action.'}
Which i dont understand cause i am doing exactly the same as in my server component with the same endpoint.
// SWR example --> Client component
const fetcher = async (url: string) => {
try {
const res = await fetch(url, {
method: 'GET',
headers: {
Authorization: `users API-Key ${process.env.API_KEY}`,
},
});
const data = await res.json();
return data.docs;
} catch (err) {
console.error(err);
}
};
const { data, error, isLoading } = useSWR(
'https://myurl.com', // my
fetcher
);
console.log(data);
if (error) return <div>failed to load</div>;
if (isLoading) return <div>loading...</div>;
return <div>hello {data}!</div>;
Do note that
process.env.API_KEY
won't work client side. Next.js only allows for environment variables prefixed
NEXT_PUBLIC_
to be included client-side.
E.g.
${process.env.NEXT_PUBLIC_API_KEY}
- however the obvious question remains: Is this secure? - Answer: no.
Client side, should NEVER fetch data from an API passing persistent secure credentials. If you initialise a session on the client and pass a temporary access token, it can be argued to be more secure as the token is temporary, but the API key is not.
If the data you are trying to fetch is supposed to be publicly available, you could update your access control in Payload to allow public read of your records - but if they are supposed to be securely accessed only by your service, I would advice adding an API proxy on your Next.js site.
I.e. Create an API route in Next.js which you can call from your client-side without any credentials, and then execute the secure API call passing API keys from your server-side code to your CMS and return the response back to the client.
Ah i see, makes sense and it works now. Thanks a lot for the detailed explanation.
Star
Discord
online
Get dedicated engineering support directly from the Payload team.