Spring Cloud Gateway is a reactive API gateway built on Spring WebFlux and Project Reactor. It provides routing, filtering, and cross-cutting concerns for microservices.

Setup

  <dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
  

Basic Routing

  spring:
  cloud:
    gateway:
      routes:
        - id: user-service
          uri: lb://user-service
          predicates:
            - Path=/api/users/**
          filters:
            - StripPrefix=0

        - id: order-service
          uri: lb://user-service
          predicates:
            - Path=/api/orders/**
          filters:
            - StripPrefix=0
            - AddRequestHeader=X-Gateway, true
  

lb:// uses client-side load balancing via service discovery.

Predicates

Predicate Example
Path Path=/api/users/**
Method Method=GET,POST
Header Header=X-Request-Id, \d+
Query Query=name, alice
After After=2024-01-01T00:00:00Z

Filters

  filters:
  - AddRequestHeader=X-Request-Source, gateway
  - AddResponseHeader=X-Response-Time, ${responseTime}
  - RewritePath=/api/v1/(?<segment>.*), /${segment}
  - RequestRateLimiter=10, 20, 1s  # 10 req/s, burst 20
  - CircuitBreaker=myCircuitBreaker
  

Custom Filter

  @Component
public class AuthGatewayFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String token = exchange.getRequest().getHeaders().getFirst("Authorization");
        if (token == null || !isValid(token)) {
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() { return -1; }
}
  

CORS Configuration

  spring:
  cloud:
    gateway:
      globalcors:
        cors-configurations:
          '[/**]':
            allowedOrigins: "https://myapp.com"
            allowedMethods: "*"
            allowedHeaders: "*"
  

Best Practices

  • Use Gateway as the single public entry point
  • Apply authentication/authorization at the gateway level
  • Configure rate limiting to protect backend services
  • Use circuit breaker filters for resilience
  • Keep gateway logic thin — no business logic