Add CORS Headers

If you want to build a remote API server, you must handle CORS request to make sure remote browser can access your server.

Windwalker has a CorsHandler to quickly add CORS headers to Response. Fo example, you can do this in controller:

// In Controller

use Windwalker\Core\Http\CorsHandler;

// Response object is immutable
// Make sure you return response to replace old one
$this->response = CorsHandler::create($this->response)
    ->allowMethods(['GET', 'POST'])
    ->allowHeaders(['X-Foo', 'X-bar'])

Now Windwalker will auto genarate these headers:

Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: X-Foo, X-Bar
Access-Control-Allow-Methods: GET, POST
Access-Control-Allow-Origin: *

Dynamically Return Allow Origins

Use wildcard (*) to Allow-Origin is not recommended, you can save domains which you allowed in system and add them to header dynamically.

$allowOrigins = $repo->getMyAllowOrigins();

$origin = $this->input->server->getUrl('HTTP_ORIGIN');

if (in_array($origin, $allowOrigins)) {
    $this->response = CorsHandler::create($this->response)

You can also add multiple origins:

$this->response = CorsHandler::create($this->response)

The headers will be:


To replace all origins, set true to second argument.

$this->response = CorsHandler::create($this->response)
    ->allowOrigin($newOrigin, true)

Use CoreTrait

Use CorsTrait on controller to add some helper methods:

class GetController extends AbstractController
    ue JsonApiTrait, CorsTrait;

    public function preparExecute()

If you found a typo or error, please help us improve this document.