CORS

Browsers use Cross-Origin Resource Sharing (CORS) to decide whether frontend code can read a response from another origin. Enable CorsMiddleware when, for example, a frontend at https://app.example.com calls an API hosted at https://api.example.com.

Registration

Add the middleware to the application's existing middlewares() hook. Global registration lets Atom handle a preflight before route matching, so the API needs no separate OPTIONS route.

app/Application.php (excerpt)
use Atom\Http\CorsMiddleware;
use Atom\Http\MiddlewareRegistry;

protected function middlewares(MiddlewareRegistry $middlewares): void
{
    $middlewares->add(CorsMiddleware::class);
}

If you also use a global rate limiter, register CORS first so preflights are handled before the limiter runs.

Configuration

List the frontend origins that can call the API. An origin includes the scheme, hostname, and port if it differs from the default. Use the frontend's origin in CORS_ALLOWED_ORIGINS.

.env
CORS_ALLOWED_ORIGINS=https://app.example.com,https://admin.example.com
CORS_ALLOWED_METHODS=GET,POST
CORS_ALLOWED_HEADERS=Content-Type,Authorization

Allow only the methods and request headers the frontend needs. Atom allows no origins by default. For an allowed origin, it sets Access-Control-Allow-Origin to that origin and adds Vary: Origin. To allow browser requests with credentials such as cookies, set CORS_ALLOW_CREDENTIALS=true and list the allowed origins explicitly.

How preflight works

For some cross-origin requests, the browser sends an OPTIONS request first. It includes its Origin, the intended HTTP method in Access-Control-Request-Method, and any requested headers in Access-Control-Request-Headers.

Atom checks those values against the configured lists. If they are allowed, it returns 204 No Content with the applicable CORS headers. If a value is disallowed, it returns 403 Forbidden. In both cases, the preflight ends before the route handler.

On the subsequent request, Atom runs the route normally and adds CORS headers for an allowed origin. An ordinary request from a disallowed origin can still reach the application, and Atom omits the CORS headers. Keep authentication and authorization on the API routes themselves.