I'm using the CMS template and am now trying out the corresponding front end and it hits the following issue:
host:8000/api/graphql' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
index.tsx:75
I have a general understanding of CORS but am curious of the best path forward within Payload to make this work. TIA.
no I haven't, do you have any recommendations on how to do this?
Have you installed CORS and added it as a middleware in your server.js/server.ts?
Yeah, just run
npm install cors
on your project, and in the server.js add
const cors = require('cors')
to your imports, and
app.use(cors())
to your middleware
Here's an example of what my server.js looks like
const express = require('express');
const payload = require('payload');
const cors = require('cors')
const router = express.Router();
const app = express();
require('dotenv').config();
// Redirect root to Admin panel
app.get('/', (_, res) => {
res.redirect('/admin');
});
//middleware
app.use('/api', router)
app.use(cors())
app.use(express.urlencoded({extended: true}))
app.use(express.json())
// Initialize Payload
payload.init({
secret: process.env.PAYLOAD_SECRET,
mongoURL: process.env.MONGODB_URI,
express: app,
onInit: () => {
payload.logger.info(`Payload Admin URL: ${payload.getAdminURL()}`);
},
});
// Add your own express routes here
app.listen(process.env.PORT);
Have you got something like this in your payload.config.ts
cors: [
'http://localhost:3000',
PAYLOAD_PUBLIC_APP_URL,
].filter(Boolean),
Exactly, you can define
cors
directly within your Payload config. Here are the docs for that:
https://payloadcms.com/docs/configuration/overviewCustom CORS middleware would really only be necessary for something like custom root endpoints described here:
https://payloadcms.com/docs/rest-api/overview#custom-endpointsI'm a year late to the party and using V3 but I'm running into this issue with custom endpoints on collections. cors and csrf are set up in the config as per the documentation but the only way I've got a custom endpoint to work is by adding custom cors headers to the custom endpoint response, which doesn't seem ideal. I know the docs say you're responsible for securing your own endpoints, but what does that actually mean?
Same here. Custom endpoint CORS need setup by nextjs
Star
Discord
online
Get dedicated engineering support directly from the Payload team.