Building API Gateways with Spring Cloud Gateway, Nacos, and Custom Filters
Dependencies
Add the following starters to your pom.xml (or equivalent Gradle coordiantes):
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
These modules enable service registration with Nacos and reactive gateway capabilities.
Service & Route Configuration
Below is a minimal application.yml that registers the gateway in Nacos and defines two load‑balanced routes:
server:
port: 10010
spring:
application:
name: gateway-service
cloud:
nacos:
server-addr: localhost:8848
discovery:
namespace: 16035e26-9a58-403c-9308-083325c0f8ee
gateway:
routes:
- id: users-route
uri: lb://userservice
predicates:
- Path=/user/**
- id: orders-route
uri: lb://orderservice
predicates:
- Path=/order/**
uri: lb://<service-name>enables client‑side load balancing through the service registry.- Static URIs such as
http://127.0.0.1:8081are also supported. - Predicate names (e.g.,
Path) are case‑sensitive.
Official route predicate factories are documented in the Spring Cloud Gateway reference.
Route‑Specific and Default Filters
GatewayFilter instances operate on both incoming requests and outgoing responses. You can attach them to individual routes or apply them globally.
spring:
cloud:
gateway:
routes:
- id: orders-route
uri: lb://orderservice
predicates:
- Path=/order/**
filters:
- AddRequestHeader=X-Request-Source, ordermanagement
default-filters:
- AddRequestHeader=X-Request-Source, gateway-global
- Filters listed under a specific route only affect that route.
default-filtersare applied to every route defined in the gateway.
Custom Global Filter
Implement GlobalFilter to define logic that runs for every request. The example below checks for a query parameter named access_token:
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
@Order(-1)
@Component
public class TokenValidationFilter implements GlobalFilter {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
String token = exchange.getRequest()
.getQueryParams()
.getFirst("access_token");
if ("secret-2025".equals(token)) {
return chain.filter(exchange);
}
exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
return exchange.getResponse().setComplete();
}
}
avian orders define the filter chain priority. Lower numeric values mean earlier execution.
Filter Execution Order
- Priority is determined by
@Orderor theOrderedinterface; smaller values run first. - When two filters share the same order, the sequence is: default filters → route‑specific filters → global filters.
Cross‑Origin (CORS) Configuration
Gateways often need to handle browser cross‑domain requests. Enable global CORS settings in application.yml:
spring:
cloud:
gateway:
globalcors:
add-to-simple-url-handler-mapping: true
cors-configurations:
'[/**]':
allowedOrigins:
- "http://client-app:8090"
- "http://www.example-shop.com"
allowedMethods:
- GET
- POST
- PUT
- DELETE
- OPTIONS
allowedHeaders: "*"
allowCredentials: true
maxAge: 360000
- Setting
add-to-simple-url-handler-mappingpreventsOPTIONSpreflight requests from being blocked. -itable origins, methods, headers, and cookie handling can be tuned per path pattern.