Hi, I have setup my nextjs app on digital oceans app platform.Everything is working fine but i’m getting cors erros even though I have whitelisted them with ENV variables. For example, in my server file
// CORS
const corsOptions = {
origin(origin, callback) {
if (!origin || process.env.WHITELIST.split(',').indexOf(origin) !== -1) {
callback(null, true)
}else {
callback(new Error('Not allowed by CORS'))
}
}
}
console.log(`CORS ALLOWED: ${process.env.WHITELIST}`)
server.use(cors(corsOptions));
And in my env files(also set from digital ocean platform) WHITELIST=http://localhost:3030,https://someUniqidentifier.ondigitalocean.app
Is there something i’m missing? The console.log is showing the correct whitelisted urls.
These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.
Hi! Looking at the CORS middleware documentation, it looks like the origin
function is meant to return a list of allowed origins. Since you have that ready through the environment variable, you should be able to pass them directly like so:
// CORS
const corsOptions = {
origin: process.env.WHITELIST ? process.env.WHITELIST.split(',') : [],
}
console.log(`CORS ALLOWED: ${process.env.WHITELIST}`)
server.use(cors(corsOptions));
If the environment variable is not set, this will disallow all origins. You can replace the []
default value at the end of the line with '*'
to allow all origins instead.
Does that work?
Click below to sign up and get $100 of credit to try our products over 60 days!
Actually it was on my side, I had a whitespace in my ENV variable which wasn’t read properly for the whitelist.