How To Enable CORS in CodeIgniter 4 for REST APIs

Share this Article
Reading Time: 5 minutes

CodeIgniter 4 provides several functionality. We can use CodeIgniter 4 to create REST APIs. Inside this article we will see the concept i.e How to enable CORS in CodeIgniter 4 for rest apis. Article contains very classified information

Cross-Origin Resource Sharing (CORS) is an HTTP-header based mechanism that allows a server to indicate any origins (domain, scheme, or port) other than its own from which a browser should permit loading resources. It Supports secure cross-origin requests and data transfers between browsers and servers.

Modern browsers use CORS in APIs such as XMLHttpRequest or Fetch to mitigate the risks of cross-origin HTTP requests.

Learn More –

Let’s get started.

CodeIgniter 4 Installation

To create a CodeIgniter 4 setup run this given command into your shell or terminal. Please make sure composer should be installed.

$ composer create-project codeigniter4/appstarter codeigniter-4

Assuming you have successfully installed application into your local system.

Environment (.env) Setup

When we install CodeIgniter 4, we will have env file at root. To use the environment variables means using variables at global scope we need to do env to .env

Either we can do via renaming file as simple as that. Also we can do by terminal command.

Open project in terminal

$ cp env .env

Above command will create a copy of env file to .env file. Now we are ready to use environment variables.

Enable Development Mode

CodeIgniter starts up in production mode by default. You need to make it in development mode to see any error if you are working with application.

Open .env file from root.

# CI_ENVIRONMENT = production

 // Do it to 
CI_ENVIRONMENT = development

Now application is in development mode.

How To Setup CORS Settings

To setup CORS settings we will create a CodeIgniter filter and then add cors settings to process request.

Open project into terminal and run this spark command.

$ php spark make:filter Cors

This command will create a filter file named Cors.php in /app/Filters folder.

Open Cors.php and write this complete code into it.


namespace App\Filters;

use CodeIgniter\Filters\FilterInterface;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;

class Cors implements FilterInterface
     * Do whatever processing this filter needs to do.
     * By default it should not return anything during
     * normal execution. However, when an abnormal state
     * is found, it should return an instance of
     * CodeIgniter\HTTP\Response. If it does, script
     * execution will end and that Response will be
     * sent back to the client, allowing for error pages,
     * redirects, etc.
     * @param RequestInterface $request
     * @param array|null       $arguments
     * @return mixed
    public function before(RequestInterface $request, $arguments = null)
        header("Access-Control-Allow-Origin: *");
        header("Access-Control-Allow-Headers: X-API-KEY, Origin,X-Requested-With, Content-Type, Accept, Access-Control-Requested-Method, Authorization");
        header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PATCH, PUT, DELETE");
        $method = $_SERVER['REQUEST_METHOD'];
        if($method == "OPTIONS"){

     * Allows After filters to inspect and modify the response
     * object as needed. This method does not allow any way
     * to stop execution of other after filters, short of
     * throwing an Exception or Error.
     * @param RequestInterface  $request
     * @param ResponseInterface $response
     * @param array|null        $arguments
     * @return mixed
    public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)

We can see we have added all CORS setting to before() method. This before() method always executes before processing any request.

Now, next we need to load inside application.

Load CORS Filter

Open Filters.php file from /app/Config folder.

Search for $aliases. Add these lines into it.


use App\Filters\Cors;


public $aliases = [
     'csrf'     => CSRF::class,
     'toolbar'  => DebugToolbar::class,
     'honeypot' => Honeypot::class,
     'cors'     => Cors::class,   

Search for $globals. Add this line into it.

public $globals = [
    'before' => [
        // 'honeypot',
        // 'csrf',
    'after' => [
        // 'honeypot',

Now, successfully we have the done the CORS setup to CodeIgniter 4 application. You can create rest apis and use anywhere.

We hope this article helped you to learn How to enable CORS in CodeIgniter 4 for rest apis Tutorial in a very detailed way.

Buy Me a Coffee

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.