Hackforge Academy

Category: React • Beginner

Published on 05 Apr 2026

Explanation

What is CORS: Cross-Origin Resource Sharing (CORS) allows a frontend application (like React running on localhost:3000) to access backend APIs (like Spring Boot running on localhost:8080).

Code Example

// Example scenario
// Frontend: http://localhost:3000
// Backend: http://localhost:8080
// Without CORS configuration, 
browser blocks the request

Explanation

Enable CORS at Controller Level: Use @CrossOrigin annotation directly on a controller class to allow requests from a specific origin.

Code Example

@RestController
@RequestMapping("/api")
@CrossOrigin(origins = "http://localhost:3000")
public class UserController {

    @GetMapping("/users")
    public String getUsers() {
        return "Users List";
    }
}

Explanation

Enable CORS for a Specific API Method: Apply @CrossOrigin annotation on a particular endpoint instead of the whole controller.

Code Example

@RestController
@RequestMapping("/api")
public class UserController {

    @CrossOrigin(origins = "http://localhost:3000")
    @GetMapping("/users")
    public String getUsers() {
        return "Users List";
    }
}

Explanation

Global CORS Configuration Using WebMvcConfigurer: Configure CORS for all controllers in one place.

Code Example

@Configuration
public class CorsConfig implements 
WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry
 registry) {
        registry.addMapping("/**")
                .allowedOrigins("
http://localhost:3000")
                .allowedMethods("GET", 
"POST", "PUT", "DELETE")
                .allowedHeaders("*");
    }
}

Explanation

Allow Multiple Origins: Configure multiple frontend applications to access backend APIs.

Code Example

registry.addMapping("/**")
        .allowedOrigins("
http://localhost:3000", 
"http://localhost:5173")
        .allowedMethods("GET", "POST", 
"PUT", "DELETE");

Explanation

Enable CORS with Credentials Support: Required when sending cookies or authorization tokens.

Code Example

registry.addMapping("/**")
        .allowedOrigins("
http://localhost:3000")
        .allowedMethods("*")
        .allowCredentials(true);

Explanation

CORS Configuration with Spring Security: Required if Spring Security is enabled in the application.

Code Example

@Bean
public SecurityFilterChain 
securityFilterChain(HttpSecurity http) 
throws Exception {
    http
        .cors().and()
        .csrf().disable()
        .authorizeHttpRequests(auth -> auth
            .anyRequest().permitAll()
        );

    return http.build();
}

Want structured learning with real projects?

Join our Weekend Live Workshop and become job-ready faster.