I have enabled guest posts for one of my collections
/api/postsbut I am worried about people sending mass post requests to this route. In my config file, I added
cors: [process.env.PAYLOAD_PUBLIC_NEXT_URL].filter(Boolean),but I can still make post requests using services like Postman directly to
/api/posts.
Is it possible to only allow post requests from my front end url?
I think you're right in setting up CORS, but the requests don't originate from a page with an URL so CORS does not apply with Postman IIRC.
Can you read
req.originfrom access control hooks and whitelist only certain domains?
This page might be useful to you as well:
https://payloadcms.com/docs/production/preventing-abuseby access control hooks you mean these hooks?
https://payloadcms.com/docs/hooks/collectionsthank you, yeah, I read that last night, I am planning to also implement recaptcha but that would be next step
oh I see what you mean, so something like this on create
create: ({ req }) => {
console.log(req.hostname)
// if it is my domain set it to true
return true
},looks like we dont have
req.originhttps://expressjs.com/en/api.html#req
, there is a
req.hostnamebut this always returns the backend part
yeah that returns the api route but doesnt include the frontend domain
Okay, here is what I did in case someone else need to implement something similar.
I created a new API route in next.js
/api/submissionto send my post submissions and where I send the post request to Payload and included a secret key in the header
method: ‘POST’,
headers: {
‘Content-Type’: ‘application/json’,
secret: `${process.env.PAYLOAD_SUBMISSION_SECRET}`,
},
...In the server side, I get that secret key and compare it before creating a post:
create: ({ req }) => {
if (req.user) return true
if (
req.headers.secret === process.env.PAYLOAD_SUBMISSION_SECRET
) return true
},This way if anyone sends a post requests, they are blocked unless it is coming from front end or if they add that secret code but because using next.js api route, abusers would not see the header has a secret key!
and once again, I just love Payload !
Great idea!
Star
Discord
online
Get dedicated engineering support directly from the Payload team.