Configuring CORS Correctly for React + Spring Boot
If you've built a React frontend talking to a Spring Boot backend, you've almost certainly met this error:
Access to fetch at 'http://localhost:8080/api/data' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
CORS (Cross-Origin Resource Sharing) is one of the most misunderstood parts of web development. The confusion usually comes from treating it as a backend-only problem, or from "fixing" it with a copy-pasted wildcard config that quietly breaks authentication later.
In my previous posts, I covered authentication flows and access control. This post fills a gap I promised to expand on: configuring CORS correctly - especially when cookies and credentials are involved, as they are in a secure JWT-in-cookie setup.
What CORS Actually Is
First, a crucial clarification: CORS is not a security feature your server imposes on clients. It is a browser mechanism that relaxes the Same-Origin Policy.
The Same-Origin Policy is a browser rule that blocks JavaScript on one origin from reading responses from a different origin. An origin is the combination of scheme + host + port.
| URL A | URL B | Same Origin? | Why |
|---|---|---|---|
| http://localhost:3000 | http://localhost:8080 | No | Different port |
| https://app.com | http://app.com | No | Different scheme |
| https://app.com | https://api.app.com | No | Different host |
| https://app.com/a | https://app.com/b | Yes | Path doesn't matter |
CORS is how a server opts in to being called from other origins, by sending specific response headers the browser checks.
Key implications:
- CORS errors happen in the browser, not on the server. The request often reaches your backend fine - the browser just blocks the frontend from reading the response.
- Tools like curl and Postman ignore CORS entirely, which is why your API "works" there but fails in React.
Simple Requests vs. Preflighted Requests
The browser treats requests differently depending on how "safe" they look.
Simple requests
A request is "simple" (no preflight) only if it meets all of these:
- Method is
GET,POST, orHEAD - Headers are limited to a short safelist (e.g.
Accept,Content-Type) Content-Typeis one ofapplication/x-www-form-urlencoded,multipart/form-data, ortext/plain
The browser sends the request directly and checks the response headers afterward.
Preflighted requests
Anything else - a PUT / DELETE, a custom header like Authorization or X-XSRF-TOKEN, or Content-Type: application/json - triggers a preflight.
The browser first sends an OPTIONS request asking permission:
OPTIONS /api/data HTTP/1.1
Origin: http://localhost:3000
Access-Control-Request-Method: PUT
Access-Control-Request-Headers: Content-Type, Authorization
The server must respond approving the method and headers:
HTTP/1.1 204 No Content
Access-Control-Allow-Origin: http://localhost:3000
Access-Control-Allow-Methods: GET, POST, PUT, DELETE
Access-Control-Allow-Headers: Content-Type, Authorization
Access-Control-Max-Age: 3600
Only if the preflight passes does the browser send the real request. Since most React apps send Content-Type: application/json and an Authorization header, you will almost always be dealing with preflighted requests.
The Credentials Problem
This is where most CORS setups break. If your app sends cookies (as in a secure JWT-in-HttpOnly-cookie design) or uses the Authorization header with credentials, extra rules apply.
On the frontend, you must explicitly opt in to sending credentials:
// Using fetch
fetch("http://localhost:8080/api/data", {
method: "GET",
credentials: "include", // sends cookies cross-origin
});
// Using axios
axios.get("http://localhost:8080/api/data", {
withCredentials: true,
});
On the backend, when credentials are involved, the browser enforces two strict rules:
Access-Control-Allow-Credentialsmust betrue.Access-Control-Allow-Origincannot be the wildcard*. It must name a specific origin.
This is the single most common CORS mistake: using allowedOrigins("*") together with allowCredentials(true). The browser will reject it. You must list explicit origins.
Configuring CORS in Spring Boot
There are several ways to configure CORS. For a real application, prefer a centralized, explicit configuration.
Recommended: Centralized CorsConfigurationSource
This integrates cleanly with Spring Security and keeps all rules in one place.
@Configuration
public class CorsConfig {
@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration config = new CorsConfiguration();
// Explicit origins - NOT "*" when credentials are enabled
config.setAllowedOrigins(List.of("http://localhost:3000", "https://app.yourcompany.com"));
config.setAllowedMethods(List.of("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"));
// Headers the client is allowed to send
config.setAllowedHeaders(List.of("Authorization", "Content-Type", "X-XSRF-TOKEN"));
// Headers the client is allowed to read from the response
config.setExposedHeaders(List.of("X-XSRF-TOKEN"));
// Required for cookies / credentialed requests
config.setAllowCredentials(true);
// Cache preflight response to reduce OPTIONS traffic
config.setMaxAge(3600L);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", config);
return source;
}
}
Wiring it into Spring Security
If you use Spring Security, you must enable CORS in the filter chain, or your configuration source is ignored.
@Bean
public SecurityFilterChain filterChain(HttpSecurity http, CorsConfigurationSource corsSource) throws Exception {
http
// Tell Spring Security to use your CORS configuration
.cors(cors -> cors.configurationSource(corsSource))
.csrf(/* your CSRF config */)
.authorizeHttpRequests(auth -> auth.anyRequest().authenticated());
return http.build();
}
Important: With Spring Security on the classpath, annotations like @CrossOrigin and a bare WebMvcConfigurer CORS setup often get bypassed because the security filters run first. Always wire CORS through http.cors(...).
The allowedOriginPatterns escape hatch
If you genuinely need wildcard-style matching with credentials (e.g. dynamic subdomains), Spring provides allowedOriginPatterns, which is permitted alongside credentials where plain * is not:
config.setAllowedOriginPatterns(List.of("https://*.yourcompany.com"));
config.setAllowCredentials(true);
Use this deliberately and narrowly - don't reach for it just to avoid listing origins.
Per-Endpoint CORS with @CrossOrigin
For simple apps without Spring Security, you can annotate controllers:
@RestController
@RequestMapping("/api/public")
@CrossOrigin(origins = "http://localhost:3000")
public class PublicController {
// ...
}
This is convenient for quick cases, but it scatters configuration across your codebase and, as noted, doesn't integrate reliably with Spring Security. Prefer the centralized approach for anything non-trivial.
Common Errors and How to Read Them
| Error / Symptom | Likely Cause | Fix |
|---|---|---|
| No 'Access-Control-Allow-Origin' header | CORS not configured, or security filter blocks OPTIONS | Add CORS config; wire it into Spring Security |
| Wildcard * + credentials rejected | allowedOrigins("*") with allowCredentials(true) | List explicit origins or use allowedOriginPatterns |
| Preflight OPTIONS returns 401 | Security requires auth on OPTIONS requests | Let Spring Security handle CORS so preflight is permitted |
| Header "not allowed by Access-Control-Allow-Headers" | Custom header not in allowedHeaders | Add the header (e.g. X-XSRF-TOKEN) |
| Cookies not sent | Missing withCredentials / credentials: include | Enable credentials on the frontend request |
| Can't read a response header in JS | Header not exposed | Add it to exposedHeaders |
Debugging Checklist
When CORS fails, work through this in order:
- Open the browser Network tab. Look for a preflight
OPTIONSrequest before your actual request. - Inspect the preflight response headers. Confirm
Access-Control-Allow-Originmatches your frontend origin exactly (scheme, host, and port). - Check for credentials mismatch. If sending cookies, verify both
allowCredentials(true)on the server andwithCredentials/credentials: "include"on the client. - Verify the method and headers are allowed. Compare
Access-Control-Request-Headersin the preflight against yourallowedHeaders. - Confirm CORS runs before auth. A 401 on the
OPTIONSrequest means your security config is intercepting the preflight. - Test with curl to isolate. If curl works but the browser doesn't, it's definitely CORS, not your endpoint logic.
Production Considerations
Never ship * for origins in production, and especially never with credentials. Maintain an explicit allowlist, ideally driven by environment-specific configuration.
Externalize origins into application properties per environment (dev, staging, prod) rather than hardcoding them. Keep the allowlist tight. Only include origins you actually serve.
Remember CORS is not authorization. It controls which origins' JavaScript can read responses in a browser - it does not authenticate users or protect against non-browser clients. Your authentication and access-control layers still do that job.
Bringing It Together
CORS feels mysterious until you internalize a few truths:
- It's a browser mechanism, not a server-side guard - errors appear client-side even when the request reaches your backend.
- Most React calls are preflighted, so your
OPTIONShandling must be correct. - Credentialed requests require explicit origins and
allowCredentials(true)- the wildcard is off-limits. - With Spring Security, wire CORS through the filter chain, or it won't apply.
Get these right once in a centralized configuration, and CORS stops being a recurring mystery.
A Note on Verification
The configuration here reflects common, modern Spring Boot and Spring Security patterns, but APIs and defaults shift across versions:
- Confirm the
HttpSecurityCORS DSL for your Spring Security version; older versions used slightly different method signatures. - Verify
allowedOriginPatternsavailability - it was introduced to address the wildcard-plus-credentials limitation and may not exist in very old versions. - Always test the actual preflight in a real browser, not just with curl or Postman, since those tools bypass CORS.
Comments
No comments yet. Start the discussion.