Skip to main content

Cross-Origin Resource Sharing (CORS)

Web browsers enforce a security mechanism called the Same-Origin Policy. This policy restricts a script loaded from one origin (like http://localhost:3000) from interacting with a resource from a completely different origin (like your Spring API running at http://localhost:8080).

By default, an external React frontend cannot execute an HTTP POST request against your Spring backend. The browser will actively block the network request and throw a massive red CORS error in the console.

Enabling CORS in Spring​

To bypass this browser security restriction globally, the backend server must securely append specific HTTP headers to the response, telling the browser: "Yes, I explicitly trust requests originating from localhost:3000."

Using @CrossOrigin​

For fine-grained control, you can apply the annotation directly over specific Controller classes or individual endpoints.

@RestController
@CrossOrigin(origins = "http://localhost:3000") // Only trust the React frontend
public class UserController {

@GetMapping("/users")
public List<User> getUsers() { ... }
}

Global Configuration​

To apply CORS rules globally across every endpoint without repeating annotations, you define a WebMvcConfigurer bean.

@Configuration
public class WebConfig implements WebMvcConfigurer {

@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**") // Apply to all API paths
.allowedOrigins("http://localhost:3000", "https://myprodapp.com")
.allowedMethods("GET", "POST", "PUT", "DELETE")
.allowedHeaders("*");
}
}