Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to have different cors configuration for development and production in laravel

Tags:

php

cors

laravel

I am having some issues setting different cors configurations for production and development in Laravel:

<?php

  return [
   /*
  |--------------------------------------------------------------------------
  | Laravel CORS
  |--------------------------------------------------------------------------
  |
  | allowedOrigins, allowedHeaders and allowedMethods can be set to array('*')
  | to accept any value.
  |
   */
  'supportsCredentials' => false,
  'allowedOrigins' => ['https://www.example.com'],
  'allowedHeaders' => ['*'],
  'allowedMethods' => ['*'],
  'exposedHeaders' => [],
  'maxAge' => 0,
];
like image 484
GrandFleet Avatar asked Apr 03 '26 03:04

GrandFleet


2 Answers

<?php
switch(env('APP_ENV')){
case 'development':
return [... config array ...];
break;

case 'staging':
return [... config array ...];
break;

case 'production':
return [... config array ...];
break;
}
like image 50
Tarek Adam Avatar answered Apr 04 '26 16:04

Tarek Adam


Let the server handle it

CORS headers can be sent by your HTTP(S) server, so you could just configure the two servers to set the headers for you. Unless you're requesting between domains or using websockets you really don't need to mess with the default CORS setup of Laravel which should use the APP_URL in the .env for settings. Even with websockets or echo, the headers that would have to change are the ones on the websocket server side.

Use the .env

The prefered way to do this is to Keep 2 different .env files, one for for development and production. In your .envs set a variable:

AllowedOringin=[https://www.example.com]
#etc.

Then in the config refer to the env and give a sensible default if it isn't set:

'allowedOrigins' => [env('AllowedOrigin',['https://www.example.com'])],
//etc.

Or check the environment

Alternatively, you can check which environment you're in and set the value in the config. This isn't considered as robust or easy to modify, but really the two are logically equivalent.

AllowedOrigin => (App::environment() == 'production') ? ['https://www.example.com'] : ['*'],
//etc.
like image 29
J. A. Streich Avatar answered Apr 04 '26 16:04

J. A. Streich