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.
Have you installed CORS and added it as a middleware in your server.js/server.ts?
@badjab326 no I haven't, do you have any recommendations on how to do this?
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);
@gregwhitworth 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/overview
Custom CORS middleware would really only be necessary for something like custom root endpoints described here:
https://payloadcms.com/docs/rest-api/overview#custom-endpointsStar
Discord
online
Get help straight from the Payload team with an Enterprise License.