# Prefix Stripping and Header Injection — API Gateway and Service Mesh

Source: https://www.geekswithgeeks.com/en/api-gateway-service-mesh/r-rewrite-headers

> Rewrite paths and add gateway-generated headers such as request IDs.

## The backend should not need to know

Public URLs and internal URLs often differ. The gateway can **strip a prefix** (`/api/v1/users` becomes `/users` for the service), add headers (**`X-Request-ID`** for tracing, **`X-Forwarded-For`** with the client address, an authenticated **`X-User`** identity), and remove sensitive headers. A unique **request ID** generated at the edge and passed through every hop lets you follow one request across logs and services. After authenticating, pass identity in a header the backend trusts **only because the gateway sets it** and the backend is unreachable except through the gateway (or via mutual TLS).

## Rewrite and headers (config)

The trailing slash in `proxy_pass http://echo_up/;` makes nginx replace the matched `/api/` prefix. Excerpt of the gateway config.

```nginx
location /api/ {
  proxy_set_header X-Request-ID $request_id;
  proxy_set_header X-Forwarded-For $remote_addr;
  proxy_set_header X-User "asha";
  proxy_pass http://echo_up/;
}
```

## What the upstream saw, run

I ran this against a real nginx 1.27 gateway in Docker, with small Node.js services as upstreams (full setup in the case study). A call to `/api/v1/users?id=7` reached the echo service as `/v1/users?id=7` (the `/api` prefix removed), with `X-User` set to `asha`, a generated request ID of 32 characters, and a forwarded-for address. The printed fields are: path, user, request id present, its length, forwarded-for present.

```bash
GET /api/v1/users?id=7
```

Output:

```
/v1/users?id=7 asha true 32 true
```

**Quiz:** Why generate a request ID at the gateway?

- [x] To trace one request across logs and services
- [ ] To encrypt the body
- [ ] To limit the rate
- [ ] To rewrite the path

*Answer:* To trace one request across logs and services. A shared ID ties together every log line produced for one request.
