Report this

What is the reason for this report?

App Platform: How to manage cors?

Posted on November 7, 2020

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.



This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

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?

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.