Full Stack 1 min read 577 views

How to Fix "CORS Policy" Errors in React with Laravel API

Troubleshoot and resolve CORS errors when connecting your React frontend to a Laravel API backend.

E
API connection illustration

The Problem

You're getting this error in your browser console:

Access to fetch at 'http://localhost:8000/api/users' from origin
'http://localhost:3000' has been blocked by CORS policy

Why This Happens

Browsers block requests from one origin (localhost:3000) to another (localhost:8000) for security. This is called the Same-Origin Policy.

Solution: Configure Laravel CORS

Step 1: Update config/cors.php

<?php

return [
    'paths' => ['api/*', 'sanctum/csrf-cookie'],
    'allowed_methods' => ['*'],
    'allowed_origins' => [
        'http://localhost:3000',
        'http://localhost:5173', // Vite
        env('FRONTEND_URL', 'https://yourapp.com'),
    ],
    'allowed_origins_patterns' => [],
    'allowed_headers' => ['*'],
    'exposed_headers' => [],
    'max_age' => 0,
    'supports_credentials' => true,
];

Step 2: Configure React/Axios

import axios from 'axios';

const api = axios.create({
    baseURL: 'http://localhost:8000/api',
    withCredentials: true, // Important for cookies!
    headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
    }
});

export default api;

Step 3: For Laravel Sanctum (SPA Auth)

// First, get CSRF cookie
await axios.get('http://localhost:8000/sanctum/csrf-cookie', {
    withCredentials: true
});

// Then login
await api.post('/login', { email, password });

Common Mistakes

  • Forgetting withCredentials: true
  • Using '*' for allowed_origins with credentials
  • Not including sanctum/csrf-cookie in paths

Production Checklist

  • Use specific origins, never '*'
  • Use environment variables for URLs
  • Test both HTTP and HTTPS
Share this article:
ES

Written by Edrees Salih

Full-stack software engineer with 9 years of experience. Passionate about building scalable solutions and sharing knowledge with the developer community.

View Profile

Comments (0)

Leave a Comment

Your email will not be published.

No comments yet. Be the first to share your thoughts!