The Problem
When developing a decoupled architecture where your frontend runs on http://localhost:3000 and your Laravel backend runs on http://localhost:8000, modern browsers automatically block requests with the dreaded error:
Access to XMLHttpRequest at 'http://localhost:8000/api/v1/user' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present.
Step 1: Configure config/cors.php Properly
In Laravel 11, CORS settings are handled directly in config/cors.php. Avoid setting wildcard * when using credentials (cookies/sessions). Update your config as follows:
return [
'paths' => ['api/*', 'sanctum/csrf-cookie', 'login', 'logout'],
'allowed_methods' => ['*'],
'allowed_origins' => [
'http://localhost:3000',
'http://localhost:5173',
'https://yourdomain.com'
],
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 86400,
'supports_credentials' => true,
];
Step 2: Initialize the CSRF Cookie Before Requests
If using Laravel Sanctum with SPA authentication, always make an initial GET request to /sanctum/csrf-cookie with withCredentials: true enabled in Axios or Fetch before triggering POST/PUT requests:
import axios from "axios";
const api = axios.create({
baseURL: "http://localhost:8000",
withCredentials: true,
headers: {
"X-Requested-With": "XMLHttpRequest",
"Accept": "application/json",
}
});
// Call this before login
await api.get("/sanctum/csrf-cookie");
const response = await api.post("/login", { email, password });
Conclusion
By defining explicit origins and properly handling the sanctum CSRF cookie handshake, your API communications will be 100% secure, compliant, and free from browser CORS errors.
Community Insights & Discussion 2 Contributions
Verified solutions, alternative approaches, and technical queries from software engineers.
The step-by-step walkthrough was exactly what our engineering team was missing. Following this implementation solved our production issue with zero downtime!
Does this same architecture pattern apply cleanly when scaling across multi-region cloud environments?
Join the Technical Discussion
Sign in to your account or connect with Google or Facebook to ask questions, share answers, and collaborate with engineers.