Skip to Content
Advanced FeaturesJavaScript Scripting

JavaScript Scripting

APXY supports custom JavaScript scripts that run against matched traffic to modify requests or responses. Scripts are executed in a goja  runtime (an embedded JavaScript engine), giving you full programmatic control over traffic transformation.

Paid feature — requires a license with script editing capability.

Concepts

Each script has:

  • A hook — when the script runs: onRequest (before forwarding to the server) or onResponse (before returning to the client)
  • A match expression — a DSL expression that determines which traffic triggers the script
  • Code — JavaScript that receives the request or response object and can modify it

CLI

Create a script

# From a file apxy script add \ --name "add-auth-header" \ --file ./scripts/add-auth.js \ --hook onRequest \ --match "host == api.example.com" # Inline code apxy script add \ --name "mask-emails" \ --code 'response.body = response.body.replace(/[\w.-]+@[\w.-]+/g, "***@***.***")' \ --hook onResponse \ --match "path contains /api/users"
FlagDefaultDescription
--nameScript name (required)
--filePath to a .js file (mutually exclusive with --code)
--codeInline JavaScript code (mutually exclusive with --file)
--hookonRequest or onResponse (required)
--matchDSL match expression (required)

List scripts

apxy script list

Remove a script

apxy script remove --id <script-id>

Enable / disable a script

apxy script enable --id <script-id> apxy script disable --id <script-id>

Web API

MethodEndpointDescription
GET/api/v1/scriptsList all scripts
POST/api/v1/scriptsCreate a new script
PUT/api/v1/scripts/{id}/enableEnable a script
PUT/api/v1/scripts/{id}/disableDisable a script
DELETE/api/v1/scripts/{id}Delete a script

Use Cases

Add authentication headers

// add-auth.js request.headers["Authorization"] = "Bearer " + env.API_TOKEN; request.headers["X-Request-ID"] = crypto.randomUUID();
apxy script add \ --name "inject-auth" \ --file ./add-auth.js \ --hook onRequest \ --match "host == api.example.com"

Mask sensitive data in responses

apxy script add \ --name "mask-pii" \ --code 'response.body = response.body.replace(/"email":"[^"]+"/g, "\"email\":\"***\"")' \ --hook onResponse \ --match "path contains /api/users"

Simulate latency for specific endpoints

apxy script add \ --name "slow-search" \ --code 'sleep(2000)' \ --hook onRequest \ --match "path contains /api/search"

Rewrite response data

apxy script add \ --name "force-feature-flag" \ --code 'var body = JSON.parse(response.body); body.features.newUI = true; response.body = JSON.stringify(body)' \ --hook onResponse \ --match "path == /api/config"
Last updated on