CORS policy setup in Dotkernel using mezzio-cors

Error message

Access to fetch at RESOURCE_URL from origin ORIGIN_URL has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

Most developers have encountered this error when interacting with APIs. In this article we will run through the steps required to fix it.

Cross-Origin Resource Sharing (CORS) is an HTTP-header based mechanism that allows a server to indicate any other origins (domain, scheme, or port) than its own from which a browser should permit loading of resources.

The library we are going to use is Mezzio CORS .


Install package Mezzio CORS

Run the following command in your application’s root directory:

composer require mezzio/mezzio-cors

Register ConfigProvider

Open your application’s config/config.php file and add the following lines to the $aggregator variable:



Register Middleware

Open your application’s config/pipeline.php file and add the following line (preferrably between ErrorHandlerInterface::class and the handler/middleware that will return your response):


Don’t forget to add the corresponding use at the top of the file:

use Mezzio\Cors\Middleware\CorsMiddleware;

Create config file

Create and open file config/autoload/cors.local.php and add the following code inside it:



use Mezzio\Cors\Configuration\ConfigurationInterface;

return [
    ConfigurationInterface::CONFIGURATION_IDENTIFIER => [
        'allowed_origins' => [
        'allowed_headers' => ['Accept', 'Content-Type', 'Authorization'],
        'allowed_max_age' => '600',
        'credentials_allowed' => true,
        'exposed_headers' => [],

Note the value ConfigurationInterface::ANY_ORIGIN stored under allowed_origins. Leaving this value as is, makes your application accessible by any origin (permissive mode). To restrict access, replace it with a list of origins that should have access to your application (restrictive mode), for example:

'allowed_origins' => [
    "", ""

Don’t forget to make a distributable version of you config/autoload/cors.local.php and add that to your repository.


Make sure your application sends the Origin header and it is set to the correct value, for example

In your config/autoload/cors.local.php:

  • when in permissive mode, you should see the expected response from the resource
  • when in restrictive mode, if the request origin is not listed under allowed_origins, you should see a 403 Not authorized response

One Comment

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>