
Dynamic API Responses: Scripting with JavaScript in APXY
Static mock rules return the same response every time. When you need to inject dynamic data, modify responses conditionally, or simulate real API behavior like rate limiting, APXY's JavaScript scripting engine handles it.
Static mock rules are the right tool for most situations: define a URL pattern, return a fixed JSON body, done. But there is a category of development scenario where "the same response every time" is not enough.
- You need to inject the current timestamp into every response
- You want to simulate a feature flag that reads from an environment variable
- You need a response body that reflects something in the request — an ID, a query param, a header value
- You want to simulate rate limiting: return 429 on every fifth request
For these cases, APXY includes a JavaScript scripting engine. Scripts run in an embedded JavaScript runtime and can read and modify requests or responses before they reach your application.
Note
JavaScript scripting is a paid feature and requires a license with script editing capability. Static mock rules are available on the free plan.
How scripts work
Each script has three parts:
- Hook —
onRequest(runs before the request is forwarded to the server) oronResponse(runs before the response is returned to your app) - Match expression — a DSL condition that filters which traffic triggers the script
- Code — JavaScript that modifies the
requestorresponseobject
Scripts are created via CLI or the Web UI. Once active, they run on every matching request automatically.
Creating your first script
Here is a script that adds an X-Request-ID header to every outgoing request to a specific API:
Create a script file:
// inject-request-id.js
request.headers["X-Request-ID"] = crypto.randomUUID();
request.headers["X-Timestamp"] = new Date().toISOString();Register it with APXY:
apxy script add \
--name "inject-request-id" \
--file ./inject-request-id.js \
--hook onRequest \
--match "host == api.example.com"Now every request to api.example.com gets those headers injected before it is forwarded to the server.
Common scripting patterns
Inject authentication for development environments
Stop hardcoding credentials in test config files. Inject them from an environment variable instead:
// inject-auth.js
request.headers["Authorization"] = "Bearer " + env.DEV_API_TOKEN;apxy script add \
--name "inject-dev-auth" \
--file ./inject-auth.js \
--hook onRequest \
--match "host == api.example.com"The env object gives scripts read-only access to environment variables.
Modify a response body to enable a feature flag
When testing a feature behind a flag, force the flag on without touching your codebase:
apxy script add \
--name "force-feature-flag" \
--code 'var body = JSON.parse(response.body); body.features = body.features || {}; body.features.newCheckout = true; response.body = JSON.stringify(body)' \
--hook onResponse \
--match "path == /api/config"Your frontend gets the config with newCheckout: true. Remove the script when you are done testing.
Mask sensitive data in captured responses
When sharing traffic captures with teammates or AI agents, mask PII before it leaves your machine:
apxy script add \
--name "mask-emails" \
--code 'response.body = response.body.replace(/"email":"[^"]+"/g, "\"email\":\"***@***.***\"")' \
--hook onResponse \
--match "path contains /api/users"Simulate rate limiting
Test how your application handles 429 responses:
// rate-limit.js
var count = (global.requestCount || 0) + 1;
global.requestCount = count;
if (count % 5 === 0) {
response.status = 429;
response.headers["Retry-After"] = "60";
response.body = JSON.stringify({ error: "rate_limit_exceeded", retry_after: 60 });
}apxy script add \
--name "simulate-rate-limit" \
--file ./rate-limit.js \
--hook onResponse \
--match "host == api.example.com"Every fifth response from api.example.com returns a 429. Your application needs to handle it correctly.
Add simulated latency to a specific endpoint
Reproduce slow response scenarios without waiting for the real API to be slow:
apxy script add \
--name "slow-search" \
--code 'sleep(2000)' \
--hook onRequest \
--match "path contains /api/search"The sleep(ms) function is available in all scripts. It pauses execution before the request is forwarded, so your application sees the full round-trip delay.
Echo request data back in the response
For debugging serialization issues, return the request body in the response so you can inspect what was actually sent:
// echo-request.js
response.body = JSON.stringify({
_debug: {
method: request.method,
path: request.path,
headers: request.headers,
body: request.body
}
});
response.status = 200;
response.headers["Content-Type"] = "application/json";Managing scripts
List all active scripts:
apxy script listDisable a script without deleting it:
apxy script disable --id <script-id>Re-enable it later:
apxy script enable --id <script-id>Delete a script:
apxy script remove --id <script-id>When to use scripts vs static mock rules
| Scenario | Use | |---|---| | Return the same JSON every time | Static mock rule | | Return different data based on request content | Script | | Simulate an error state for one endpoint | Static mock rule | | Simulate a rate limit that triggers every N requests | Script | | Inject a header into all requests | Script | | Force a feature flag on | Script | | Replace a backend endpoint with fake data | Static mock rule | | Mask PII in captured responses | Script |
Scripts are more powerful but require code. If a static mock rule covers your use case, use that first — it is simpler and available on the free plan. Reach for scripts when you need dynamic behavior or conditional logic.
For more on static mock rules, see How to Mock a REST API in 5 Minutes with APXY. For how to use captured traffic alongside your scripts, see How to Debug a Failing API Call with APXY.
Debug your APIs with APXY
Capture, inspect, mock, and replay HTTP/HTTPS traffic. Free to install.
Install FreeRelated articles
Record and Replay API Traffic for Regression Testing with APXY
Record real API traffic once, convert it to mock rules, and replay those exact responses against future code changes. Catch regressions before they reach production without maintaining a live test environment.
TutorialHow to Mock a REST API in 5 Minutes with APXY
Create a fully functional mock REST API in under five minutes. No code, no config files, no server to maintain. One command to install, one command to add a rule.