Drupal - How do I set up CORS?

I ran into this fairly recently on Pantheon, and hopefully this helps if you haven't already solved it.

cors.config:
    enabled: true
    # Specify allowed headers, like 'x-allowed-header'.
    allowedHeaders: ['x-csrf-token','authorization','content-type','accept','origin','x-requested-with', 'access-control-allow-origin','x-allowed-header','*']
    # Specify allowed request methods, specify ['*'] to allow all possible ones.
    allowedMethods: ['*']
    # Configure requests allowed from specific origins.
    allowedOrigins: ['http://localhost/','http://localhost:3000','http://localhost:3001','http://localhost:3002','*']
    # Sets the Access-Control-Expose-Headers header.
    exposedHeaders: false
    # Sets the Access-Control-Max-Age header.
    maxAge: false
    # Sets the Access-Control-Allow-Credentials header.
    supportsCredentials: true

A few things to note...

Regarding the location of the file on Pantheon, please make sure your service.yml file is in /sites/default vs just /sites. I was wrongly under the impression it would work from both places. It will only work if in the /sites/default directory.

Notice the comma separated list of allowedHeaders each in their own set of quotes. I originally had a single string like you do in your example above, and it failed countless times before I caught the subtle difference. I'm fairly certain allowedMethods works the same way if you specifically want to list out your methods.

Please also note that while my code snippet will work well for development against a Pantheon sandbox you will likely want to lock things down a bit more prior to going into production. With Pantheon offering HTTPS you will also want to make sure to use it if you are going to be passing information around through headers. Hope this helps either you if you are still having issues or someone else that stumbled upon it down the road.


Find: .../sites/default/default.services.yml

Make a copy and rename the copy to:

.../sites/default/services.yml

Find this part of the code: cors.config: enabled: false

and replace with the following - cors.config: enabled: true

Clear the cache.


The following setting working for me.

cors.config:
  enabled: true
  # Specify allowed headers, like 'x-allowed-header'.
  allowedHeaders: ['x-csrf-token','authorization','content-type','accept','origin','x-requested-with']
  # Specify allowed request methods, specify ['*'] to allow all possible ones.
  allowedMethods: ['*']
  # Configure requests allowed from specific origins.
  allowedOrigins: ['*']
  # Sets the Access-Control-Expose-Headers header.
  exposedHeaders: false
  # Sets the Access-Control-Max-Age header.
  maxAge: false
  # Sets the Access-Control-Allow-Credentials header.
  supportsCredentials: false