CORS in CodeIgniter 4, the easy way
Content Index
We're going to look at how we can connect to the Rest API in CodeIgniter from an external project, which in this example, would be the application created in Vue.
There are many ways to configure CORS in CodeIgniter 4. We'll look at the simplest way, which is 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 now, due to its simplicity. In the previous lines, we are indicating that from any origin (*):
header('Access-Control-Allow-Origin: *');HTTP requests can be made. Obviously, this is very risky and we will only leave this configuration when in development mode, but the `*` means all locations. You can also place 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 allowed HTTP methods, although based on tests, you can skip the second line. With this, you will see that the previous error no longer occurs.
As we will see later, when sending a POST, PUT, or PATCH request, the previous error reappears. This is because a preliminary request called a preflight is sent before the POST request, 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();
}⚠️ Warning about Outdated Packages
Note how long it has been since it was updated, etc. In principle, with this package, we could have easily configured the routes, although here it indicates that it is for version 4.
The problem is that there are virtually no updated packages for this.
Although installing it and adding the filter would allow defining our API routes without problems, I advise against its use.
- Risk: You are using an unmaintained package that hasn't been updated for a long time.
- Consequence: At some point, it will inevitably fail by not being compatible with the current versions of the framework or the language.
https://github.com/agungsugiarto/codeigniter4-cors
CORS Implementation in CodeIgniter
https://codeigniter.com/user_guide/libraries/cors.html
Starting from version 4.5.0 (i.e., quite advanced once version 4 came out), it was decided to implement native support for CORS (Cross-Origin Resource Sharing).
This is why I sometimes consider CodeIgniter to be a somewhat strange framework in this regard, as this functionality took a long time to integrate.
- Configuration: We will do this configuration later.
- Simplicity: The good news is that it is very simple; it literally involves adding one line of code.
I preferred not to complicate things with external packages because the native solution is simple and effective, being very similar to the functionality offered by the outdated package.
CORS in CodeIgniter 4, the correct way
Final CORS Configuration in CodeIgniter
Having finished the implementation in Vue (at least the essential part), the next crucial step is to adequately configure CORS (Cross-Origin Resource Sharing) in the backend.
1. ⏳ Context and Critique of the Implementation
As I already mentioned, native CORS support was not included from the base version of CodeIgniter 4, but was added starting from version 4.5.0.
Personal Opinion: This CORS implementation seems a bit strange to me, and the documentation on this topic is, in my opinion, somewhat abstract and not very clear.
2. Preflight Requests (Pre-request)
According to the tests we carried out earlier when configuring other headers in our Index, it is necessary to understand the concept of a Pre-request (Preflight Request).
Behavior: The documentation indicates that before making the main request (for example, to the movies route), a preliminary request (Preflight Request) is made.
Doubt: This Preflight handling is supposed to be managed internally by the framework, but according to tests, this does not happen automatically.
3. ️ Preparation for Implementation
Before proceeding, it is important that you remember to comment out or remove the previous CORS implementation we showed so that we can correctly test and verify this new native configuration.
URL used by Vue in development:
app/Config/Cors.php
'allowedOrigins' => ['http://localhost:5173'],Or if you want it to be open for all routes:
app/Config/Cors.php
'allowedOrigins' => ['*'], // Allows any origin.Create a group for your API routes and the 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 () {});Is for Preflight Requests, meaning a control request before the requests we make to the API.
You must also expose the methods that will be allowed:
app/Config/Cors.php
'allowedMethods' => ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'],You can also test using:
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 () {});
});The next step is to consume the CRUD-type REST API created in CodeIgniter 4 using a Vue app.
I agree to receive announcements of interest about this Blog.
Learn how to properly configure CORS in CodeIgniter 4. Troubleshoot errors when connecting your REST API to Vue.js using native filters and routes.