adonis.js

how to configure cors in adonis js


how to configure cors in such a way that it takes different origin when in development and production?

This is how the default cors configuration file looks like

module.exports = {
  /*
  |--------------------------------------------------------------------------
  | Origin
  |--------------------------------------------------------------------------
  |
  | Set a list of origins to be allowed. The value can be one of the following
  |
  | Boolean: true - Allow current request origin
  | Boolean: false - Disallow all
  | String - Comma separated list of allowed origins
  | Array - An array of allowed origins
  | String: * - A wildcard to allow current request origin
  | Function - Receives the current origin and should return one of the above values.
  |
  */
  origin: false,

  /*
}


Solution

  • You could simply check your NODE_ENV Environment variable. And then check if this variable is set, for example to production or development.

    Based on the CORS Documentation you can return a function. So i would check the current Environment and then return the CORS property. In your cors.js you would have something like this

    const Env = use('Env')
    ...
    ...
    origin: function (currentOrigin) {
      if(Env.get('NODE_ENV​') === 'production' {
        return currentOrigin === 'mywebsite.com'
      } else {
        true
      }
    }
    

    If the NODE_ENV is set to production only the traffic from "mywebsite.com" will be allowed, otherwise all traffic ( which is for development ).