Spring Cloud Gateway functions as the primary traffic ingress in distributed architectures, directing external requests to appropriate backend services while centralizing concerns such as authentication, rate limiting, and request transformation.
To integrate it into an existing Spring Cloud project, create a dedicated Maven or Gradle module—commonly named api-gateway. In its build descriptor, declare the starter:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
Routing behavior is controlled via application.yml. The following configuration exposes the gateway on port 8080, enables dynamic location of services registered in Nacos, and defines a single route:
server:
port: 8080
spring:
application:
name: api-gateway
cloud:
nacos:
server-addr: 127.0.0.1:8848
gateway:
discovery:
locator:
enabled: true
routes:
- id: account-route
uri: lb://account-service
predicates:
- Path=/v1/**
filters:
- StripPrefix=1
The uri value lb://account-service delegates forwarding to Spring Cloud LoadBalancer. The Path predicate restricts matching requests to those beginning with /v1/, and StripPrefix=1 removes that leading segment before the request reaches the downstream service.
Predicates determine whether an incoming request qualifies for a specific route. Common built-in predicates include:
Path— URL pattern evaluation.Method— restriction by HTTP verb such asGETorPOST.Header— requirement for specific headers, optionally evaluated with regular expressions.Host— matching against theHostheader.Query— verification of query parameter presence or value patterns.Cookie— inspection of cookie names and values.- Compound conditions — multiple predicates may be combined with implicit logical
AND.
An authorization-oriented example using the Header predicate:
routes:
- id: secure-order-route
uri: lb://order-service
predicates:
- Path=/order/**
- Header=Authorization, Bearer [A-Za-z0-9-]+
Requests lacking the expected Authorization header are rejected with a 404 Not Found.
Filters modify requests or responses as they transit the gateway. They are typically classified by execution phase:
- Pre-filter — actions before proxying, such as
AddRequestHeader,AddRequestParameter, orModifyRequestBody. - Route filter — transformations applied during proxying, including
StripPrefix,RewritePath, or circuit-breaker integration. - Post-filter — response processing like
AddResponseHeader,ModifyResponseBody, orSetStatus. - Global filter — logic executed for every route, for example custom metrics or authentication via
GlobalFilterimplementations. - Custom filter — user-defined components implementing
GatewayFilterFactoryfor reusable business logic.
A route definition combining multiple filters:
routes:
- id: inventory-route
uri: lb://inventory-service
predicates:
- Path=/warehouse/**
filters:
- StripPrefix=1
- AddRequestHeader=X-Trace-Id, gateway-node
- AddRequestParameter=region, default
StripPrefix=1 trims /warehouse, while the remaining filters inject a trace header and a default query parameter.
The application entry point is a standard Spring Boot main class:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class GatewayServerApplication {
public static void main(String[] args) {
SpringApplication.run(GatewayServerApplication.class, args);
}
}
Once started, verify behavior with an HTTP client. A browser or script targeting http://127.0.0.1:8080/v1/users is matched by the earlier account-route and proxied to account-service at /users.
A front end invocation via fetch might look like this:
fetch('http://127.0.0.1:8080/v1/users', {
method: 'GET',
headers: { 'Accept': 'application/json' }
});
With in a microservices ecosystem, the gateway assumes several operational responsibilities:
- Routing — Maps external URLs to internal service endpoints, decoupling clients from deployment details.
- Load Balancing — Distributes traffic across healthy instances using the service registry.
- Traffic Shaping — Applies rate limiting, request rewriting, and header validation at the edge.
- Fault Tolerance — Provides circuit breaking and fallback handling to prevent cascading failures.
- Unified Errors — Returns sanitized error responses, preventing internal stack traces from leaking.
- Protocol Adaptation — Translates external protocols to internal ones where necessary.
These capabilities consolidate cross-cutting infrastructure logic at the perimeter, allowing downstream services to remain focused on domain functionality.