CORS in CodeIgniter 4, the easy way - 08

Let's configure CORS in C4 in a simple way.

Let's see how we can connect to the Rest API in CodeIgniter from an external project, in this example, it would be the application created in Vue.

There are many ways to configure CORS in CodeIgniter 4, let's see the simplest way, which would be by modifying the public/index.php file:

public\index.php

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE');
***

This is the one we will use at least for the moment due to its simplicity; in the previous lines we are indicating that from any source (*):

header('Access-Control-Allow-Origin: *');

Can make HTTP requests; obviously this is very risky and we will only leave this configuration when in development mode, but the * means everywhere; you can also put the development domain:

header('Access-Control-Allow-Origin: http://localhost:5173');

With the second line:

header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE');

We indicate the types of HTTP methods allowed, although according to tests, you can do without the second line. With this, you will see that it no longer returns the previous error.

As we will see later, when sending a request of type POST, PUT, PATCH, the previous error appears again, this is because a request is sent prior to the POST called preflight, which verifies the CORS configurations and which must have a configuration like the following:

public\index.php

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE');
***
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
   header('Access-Control-Allow-Origin: *');
   header('Access-Control-Allow-Methods: POST, GET, DELETE, PUT, PATCH, OPTIONS');
   header('Access-Control-Allow-Headers: token, Content-Type');
   header('Access-Control-Max-Age: 1728000');
   header('Content-Length: 0');
   header('Content-Type: text/plain');
   die();
}

That they practically do not exist, notice. It has been a long time since it was updated and so on, and in principle with this package we could easily configure them, although I do not know if this is for the three. No, here it says four. There we install it, we continue, we add, in this case there is a filter, we indicate what the routes of our Api are going to be and well, that would be practically everything and there we could use it without any problem, but it is not necessary, it is an outdated package, therefore, if you do not update it, I advise against its use because you are using a package without maintenance. And at some point it will fail, but notice that

https://github.com/agungsugiarto/codeigniter4-cors

Starting with version 4.5.0, that is to say, quite advanced, once version 4 was released, they decided to implement the use of CORS and this is why I say that sometimes CodeIgniter is a slightly strange framework in that sense, we will do this configuration later, but again, since it is simple, it was literally just adding a line of code, so I preferred not to complicate things too much with this, which is not very complicated either, but notice that it is similar to the package:

https://codeigniter.com/user_guide/libraries/cors.html

CORS in CodeIgniter 4, the right way

Now that the implementation with viw is finally finished, at least the part that I wanted to implement, the next thing we want to do is configure the cors in the correct way, so to speak, so as I was telling you, it is a feature that was not released when CodeIgniter 4 came out, as indicated here, it came out from version 4. 5. Here are a few criticisms before showing the implementation, I want to comment on a few things.

Remember to comment or remove the implementation that we showed above to test this implementation.

This part of the documentation is a bit abstract and the documentation does not help, so I understand that what I am indicating here is what was the prel request, that is, the request before the request, again before making this request, for example, this one about movies, it makes a previous request according to the tests we did previously, which was when we configured the rest of the headers in our Index, so I understand that is why it does not ask for them, it should not be done internally. But well, that is how it works, I don't know, a little bit of my opinion, I am giving you here a little bit of my opinion and also the implementation.

used by Vue:

app/Config/Cors.php

'allowedOrigins' => ['http://localhost:5173'],

Or if you want it to be open to all routes:

app/Config/Cors.php

'allowedOrigins' => ['*'], // Allows any origin.

Create a bundle for your API routes and CORS middleware:

app/Config/Routes.php

$routes->group('', ['filter' => 'cors'], static function (RouteCollection $routes): void {
  
   $routes->group('api', ['namespace' => '\App\Controllers\Api'], function ($routes) {
       $routes->resource('pelicula');
       $routes->resource('categoria');
   });
   
   $routes->options('api/(:any)', static function () {});
});

This route:

$routes->options('api/(:any)', static function () {});

This is for Preflight Requests, that is, a control request before the requests we make to the API.

Also, you must expose the methods that can be used:

app/Config/Cors.php

'allowedMethods' => ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'],

You can also try by:

app/Config/Routes.php

$routes->group('', ['filter' => 'cors'], static function (RouteCollection $routes): void {
  
   $routes->group('api', ['namespace' => '\App\Controllers\Api'], function ($routes) {
       $routes->resource('pelicula');
       $routes->resource('categoria');
   });
   $routes->options('api/(:any)', static function () {
       // Implement processing for normal non-preflight OPTIONS requests,
       // if necessary.
       $response = response();
       $response->setStatusCode(200);
       $response->setHeader('Allow:', 'OPTIONS, GET, POST, PUT, PATCH, DELETE');

       return $response;
   });
   // $routes->options('api/(:any)', static function () {});
});

- Andrés Cruz

En español

This material is part of my complete course and book; You can purchase them from the books and/or courses section, Curso y Libro CodeIgniter 4 desde cero + integración con Bootstrap 4 o 5 - 2025.

Andrés Cruz

Develop with Laravel, Django, Flask, CodeIgniter, HTML5, CSS3, MySQL, JavaScript, Vue, Android, iOS, Flutter

Andrés Cruz In Udemy

I agree to receive announcements of interest about this Blog.

!Courses from!

10$

On Udemy

There are 1d 04:22!


Udemy

!Courses from!

4$

In Academy

View courses

!Books from!

1$

View books
¡Become an affiliate on Gumroad!