This module is concerned with implementing cross origin resource sharing policies by domain and by method. By default, all browsers enforce a same origin policy, meaning that resources can only be accessed by other requests from the same origin. There are two ways to get around this: with JSON with Padding (JSONP), which is generally considered to be an insecure practice, or with a formal cross-origin resource sharing policy (CORS)


const cors = require('cors')
  • _spartan assumes a same-origin policy by default and, thus, resource sharing is disabled in the default security policy (e.g. resourceSharingPolicy.corsSettings.enabled = false). As such, if you use the default policy, cors.js will not be included in the boilerplate code offerings on the first pass. To change this, you’ll need to change resourceSharingPolicy.corsSettings.enabled : true in security.json and then run _spartan --force to get cors.js to populate in the security file.
  • _spartan uses the cors npm module to configure cors settings


Module Instantiation

method name description params returns
N/A returns a pre-configured cors module based upon the policy N/A cors(corsOptions) function or Error


// ex: in app.js -> 
const cors = require('./security').cors

Using CORS

method name description params returns
cors() sets the cors headers as configured in the policy N/A Error

The cors.js module will make every attempt to take the domains defined in the content security policy See security headers.js and map them into the cors whitelist, including the domains with * designations (meaning subdomains). In the spirit of thoroughness, you should go through this list (found at resourceSharingPolicy.corsSettings.config.whitelist) to make sure that all affected subdomains are represented.


You can use CORS by route or for every route

// on every route
// where app = express() or similar
app.get('/route', cors(), function(request, response, next){


  • (‘cors/disabled-by-policy’) => thrown if the resource sharing policy object is not enabled. To change this, change resourceSharingPolicy.corsSettings.enabled : true in security.json
  • (‘cors/whitelist-subdomain-transform’) => thrown if there was a problem converting the subdomains defined in the whitelist to regex
  • (‘cors/origin-not-allowed’) => thrown if there a request came in from an origin not on the whitelist