# Stale While Revalidate Caching for Third Party REST Apis

> REST API rate limits hit fast from Frontend / Web. Cache 300s on GET calls where the query string scopes the response.

- Canonical page: https://realcomposer.com/recipes/stale-while-revalidate-third-party-api
- Client platform: Frontend / Web
- Upstream services: REST API
- Category: Edge Caching & Rate Limits
- JSON version: https://realcomposer.com/recipes/stale-while-revalidate-third-party-api.json
- Install in RealComposer (free plan, pre-fills this pipeline): https://realcomposer.com/dashboard/pipelines/new?recipe=stale-while-revalidate-third-party-api&via=agent

## Problem: REST API rate limits from Frontend / Web traffic

Without edge caching, identical REST API reads during a session still round-trip to the origin.

- HTTP 429 responses during launch traffic
- Surprise SaaS overages from duplicate reads
- Slower repeat views than necessary

## Solution steps

1. **Bind vault keys to the Worker**: Create API_BEARER_TOKEN vault entries, then bind them to this pipeline step headers with {{secrets.NAME}} placeholders.

2. **Configure upstream steps and output mapping**: Configure headersTemplate to inject vault secrets, target https://jsonplaceholder.typicode.com/users/{{query.userId}}, and Add output mapping fields that mirror the JSON contract your screen already expects.

3. **Call from Frontend / Web**: Authorize with Bearer rc_live_ and fetch the mapped JSON contract your UI already expects.

```
const res = await fetch('https://realcomposer.com/v1/workspace/stale-while-revalidate-third-party-api', {
  headers: { Authorization: 'Bearer rc_live_your_token' }
});
```

## Pipeline config

Import this config into a RealComposer pipeline. `{{secrets.NAME}}` values are read from the encrypted Secret Vault at request time, so the client never sees them.

```json
{
  "name": "Stale While Revalidate Caching for Third Party REST Apis",
  "method": "GET",
  "cacheTtlSeconds": 300,
  "authMode": "client_token",
  "steps": [
    {
      "stepKey": "upstream",
      "upstreamUrlTemplate": "https://jsonplaceholder.typicode.com/users/{{query.userId}}",
      "httpMethod": "GET",
      "headersTemplate": {
        "Authorization": "Bearer {{secrets.API_BEARER_TOKEN}}"
      },
      "timeoutMs": 3000
    }
  ],
  "outputMapping": {
    "version": 1,
    "fields": [
      {
        "targetPath": "userId",
        "sourcePath": "id",
        "type": "number",
        "sourceStep": "upstream"
      },
      {
        "targetPath": "name",
        "sourcePath": "name",
        "type": "string",
        "sourceStep": "upstream"
      },
      {
        "targetPath": "email",
        "sourcePath": "email",
        "type": "string",
        "sourceStep": "upstream"
      }
    ]
  }
}
```

## Call the pipeline

```bash
curl -X GET "https://realcomposer.com/v1/workspace/stale-while-revalidate-third-party-api" \
  -H "Authorization: Bearer rc_live_client_token"
```

## Payload before and after

Raw upstream response:

```json
{
  "requestId": "req_stale-wh",
  "upstreamLatencyMs": 142,
  "audit": {
    "region": "edge",
    "trace": "stale-while-revalidate-third-party-api"
  },
  "payload": {
    "id": "sample_id",
    "status": "active",
    "nested": {
      "tags": [
        "demo"
      ],
      "internal": true
    },
    "unused_blob": {
      "foo": "bar",
      "bar": "baz"
    }
  }
}
```

Slimmed RealComposer response:

```json
{
  "userId": "sample",
  "name": "sample",
  "email": "sample"
}
```

## FAQ

### What should Frontend / Web store instead of REST API secrets?

Use scoped tokens where the vendor allows them on stale-while-revalidate-third-party-api. Admin keys stay {{secrets.*}} references only.

### How do I forward JSON bodies to POST upstreams?

Cache key for stale-while-revalidate-third-party-api: internal edge-cache path plus sorted query. Identical params hit; vary userId per user.

### How do I rotate upstream credentials?

Allowed origins on the stale-while-revalidate-third-party-api client token restrict which domains may call the edge URL.
