nitrojs / nitro

Next Generation Server Toolkit. Create web servers with everything you need and deploy them wherever you prefer.
https://nitro.build
MIT License
6.3k stars 520 forks source link

How to add cors settings (origin)? #2903

Open MickL opened 2 days ago

MickL commented 2 days ago

Describe the feature

At the moment I have the following rule in my nitro.config.ts:

routeRules: {
    '/**': {
      cors: true,
    },
  },

I want to only accept cors for my website-domain (prod and dev). How can I make options like cors origin in Nitro? Unfortunately the whole cors topic is not covered in the docs.

E.g. my domain is www.example.com and my api is at api.example.com -> Without cors: true this results in errors.

Additional information

Shooteger commented 2 days ago

This should help, https://github.com/nitrojs/nitro/issues/539

Official docs for routeRules shows how to handle special routes in dev or prod individually: https://nitro.build/config#routerules

You could use devProxy, if I understand correctly what you want to achieve on localhost:

{
  devProxy: {
    '/proxy/test': 'http://localhost:3001',
    '/proxy/example': { target: 'https://example.com', changeOrigin: true }
  }
MickL commented 2 days ago

I have no problem making a differntiation between dev and prod. I want to set cors origin to a specific URL instead of accepting all origins.

For example in Express cors has an options attribute where you can set origin and other things. You could even use an async function for this:

var corsOptions = {
  origin: function (origin, callback) {
     db.loadOrigins(function (error, origins) {
      callback(error, origins)
    })
  }
}

app.use(cors(corsOptions));

What I am looking for is something like this:


routeRules: {
    '/**': {
      cors: {
           origin: 'www.example.com'
      },
    },
  },