This page presents examples of scripts that can be used in Custom JavaScript interceptors.
The examples demonstrate common usage scenarios in the gateway, such as:
This script can be used to block access to an old URL, but with a friendly message to developers still using that URL.
You should follow the scripts below, adding the URL to the URL Pattern field.
This snippet indicates that the Gateway will not accept the request. It must be added to the request flow.
Add the following snippet, modifying the response to set a 404 status code and fixed body.
It should be executed in the after-response step.
In this example, a new attribute was included in the object $call, enabling the interruption of the request flow at each point, thus returning the response to the client.
To stop the request and return the response without going to the backend and executing the response flow, add this script:
To interrupt the request or response, making the request to the backend:
This script can be used to add a header to the request.
In the example below, we are inserting a Content-Type: application/json only if the request does not contain a Content-Type.
This script can be used to add a header to a request.
The content of this header will be obtained from the extraInfo of one of the tokens used in the request.
In the example below, a header X-Customer-Id will be added, containing the client ID represented by the existing access token.
To test the script above, make the following request.
This test assumes that there is an access token with the code mycustomer containing an extraInfo called customerId and value 123.
Among the headers received by the backend, there must be:
See that in the script above we are assuming that there will always be an access token. If the script is executed in the request flow and the access token is required (as it usually is), then this is a sound assumption, since the gateway would block the access if the token was not informed.
If the token is optional, however, we must deal with the case of it not being informed. The example below adds a header indicating that this app is being tested in a sandbox environment, but the app might not be informed.
To test the script above, make the request below.
This test assumes that there is an app with the code myapp, containing an extraInfo called isSandbox and value true.
Among the headers received by the backend, there must be:
This is a script to modify an Authorization header.
In the example below, the client is sending an Authorization header with this content: Basic YWJjZGVmCg==.
Decoding the Base64 value, we obtain abcdef, but with a newline (\n) at the end.
We will remove the Basic part, decode the rest of the value in Base64, remove the newline, and encode again:
In this example, we have a backend that always expects to receive pagination parameters in query-strings (e.g., /products?page=5&page_size=10).
But we want requests without these parameters to be executed with sensible default values (page=0 and page_size=10, for instance).
Note that we do not want to add parameters if they already exist.
We also want to protect ourselves against calls that specify pagination parameters beyond the expected, so we must continue the script above with:
Obtain a parameter from the URI and add it to the request body
Capture a PATH parameter
This example demonstrates how to capture a parameter defined in the request PATH.
Transformation with JSON sub-elements and JSON array
This example receives a request in the properties format (a subset of YAML):
We want to convert it to a JSON, as the one below:
For such, let us execute the following script in the request flow:
TIPThe default interceptor TXT to JSON can be used to carry out this transformation.
In this example, the client sends a request in a format that is a bit old; in the new format, a field has changed names. We only want to translate the old name into the new one:
The script must be executed in the request flow, so that it runs before the call is forwarded to the backend.
The script can be tested pointing to an endpoint that echoes what was received:
The result must include the body received:
The following code unpacks the request body compressed using gzip.
This transformation must be applied to the request flow.
Stop the execution flow in the request and return the response to the client
Treat back-end exceptions
In this example, we have an API at the backend which returns a JSON response, but we want to set up an equivalent XML to return to the client.
TIPThe default interceptor JSON to XML can be used to carry out this transformation.
This script must be executed in the response flow.
With a bit more code, we can make the function toXml() deal with object lists, complex objects, etc.
This script creates an XML using JDOM and adds it to the response.
This section describes how to access environment variables in a Custom JavaScript in the API Gateway and presents the main objects and commands available.
When to use
Use environment variables when the same interceptor needs to change behavior across environments without requiring changes to the JavaScript code. Common examples include:
How to access environment variables
Environment variables are available through the $call.environmentVariables object, which is a Map<String, String>.
The most common access pattern is:
Simple example
Example with required validation
When the variable is required, validate it before using it:
Example building a dynamic URL
Building a response body without using backticks (`)
The Custom JavaScript runtime uses the Rhino engine (org.mozilla.javascript) with Context.VERSION_1_8. In practice, this means that the supported syntax does not match modern JavaScript used in browsers or Node.js.
For this reason, avoid ES6+ features in the interceptor. In particular, do not use template literals with backticks:
Instead, prefer one of the following alternatives:
The second option is the safest way to generate JSON because it avoids escaping and string concatenation errors.
Global objects available in the script
The objects below are injected by the gateway into the Custom JavaScript scope.
Object | Primary use | Most common methods/operations |
|---|---|---|
$call | Full call data | environmentVariables.get(...), decision.setAccept(...), contextVariables.put(...), addContextVariables(...) |
$request | Current request | getHeader(...), setHeader(...), addHeader(...), getQueryParam(...), setQueryParam(...), setMethod(...), getBody().getString(...) |
$response | Current response | setStatus(...), setHeader(...), getBody().setString(...), getBody().getString(...) |
$http | HTTP calls from within the script | get(...), post(...), put(...), delete(...), patch(...) |
$console | Interceptor debug log | debug("key", value) |
$base64 | Base64 encode/decode | btoa(...), atob(...) |
$json | JSON Java/JS conversion | parse(...), stringify(...) |
$cookies | Cookie reading | parseRequestCookieValues(...), parseResponseCookieValues(...) |
$jdom | XML manipulation | parse(...), findElements(...), stringify(...) |
$gzip | Compression/decompression | compress(...), decompress(...) |
$billing | Billing trigger | execute($call) |
$jwt | JWT encode/decode | encode(payload, secret), decode(token, secret) |
Config | Gateway configuration access | getString(...), getBoolean(...), getInteger(...), getLong(...), contains(...) |
IMPORTANT
$compositionResponseonly exists in composition flows.environmentVariablesstores values asString. If you need a number, explicitly convert it usingparseInt(...),parseFloat(...), orNumber(...).contextVariablescan be used to share data with other interceptors or flow stages.
Most common $http signatures
Gateway tests validate the following formats:
NOTE
headerscan be a simple JavaScript object, for example{ "content-type": "application/json" }.timeoutis handled in seconds in the context of the custom interceptor.- The return type is a
RESTResponse, with methods such asgetStatus(),getHeaders(), andgetResponseText().
Complete example
The example below shows a common scenario: reading an environment variable, calling a backend, and returning a controlled response in case of error.
Best practices
var and classic JavaScript syntax to maintain compatibility with the current engine.JSON.stringify(...) instead of manually concatenating strings.$console.debug("key", value) when the interceptor has debug enabled."UTF-8".Quick summary
If the only question is "how to read an env var in Custom JS?", the essential line is:
If this variable is used to build a JSON response, avoid backticks. Use JSON.stringify(...) or simple string concatenation.
Validate URL against extraInfo
In this example, we will create a script to be executed only for the URLs of the type /projects/*.
This pattern must be inserted in the field URL Pattern.
This API returns a list of members of a given project.
However, each access token can only see certain projects.
The list of allowed projects is stored in the token's extraInfo, at the moment of registration.

NOTEThe
extraInfocan be read in interceptors but is not persisted when modified at runtime. Values must be defined at the time of token creation/registration.
If the token above is used to call /projects/marketing-site or /projects/product-support, it must be allowed access; but if it tried to call /projects/ui-redesign, we want it to be barred with an "HTTP 403 Forbidden" error and a message providing explanation.
As we need the token extracted and validated, we will insert the script in the request flow:
With this script and token, these are the expected results:
Obtain token from extraInfo
In the example below, we have some legacy clients that cannot modify their systems to send OAuth 2.0 access tokens.
Instead, they need to keep on sending a username/password pair in a proprietary header X-User-Password.
We want to recover this header, extract the data, and set up a new Authorization header with codes that we already know.
For the Gateway, everything happens as if the legacy system had sent an Authorization header, as the other systems.
Therefore, this script needs to be executed in the request flow.
As we know that only three legacy systems are working this way, we will perform a hard-coded validation of the credentials.
Compare the extraInfo value with the API resource value
In this example, the route to be followed differs depending on a flag in the extraInfo of an access token indicating whether it is a legacy or not.
If so, it should be routed to http://legacy.mycompany.com; if not, it should be forwarded to http://api.mycompany.com.
Note that at least one route must be defined, otherwise the Gateway will consider the request as irregular and will return an HTTP 404 status code before the script is executed.
As a test, you can create an app with the extraInfo isLegacy = true and make a request.
After, modify the flag (or create another app with isLegacy = false) and make another request.
The first request, by a modern app, should hit http://example.demo.sensedia.com/example/api.
The second request, by a legacy app, should be routed to http://legacy.backend.com.
The best way to execute other services is running the Service Mashup interceptor. However, it is also possible to execute them with custom interceptors.
This script orchestrates services, which can be called in any flow (request or response).
In some scenarios, it may be necessary to execute multiple operations in parallel within an interceptor, for example when querying different external services during the transformation of a request.
Since the Custom JavaScript runtime uses the Rhino engine, it is possible to directly access Java classes available in the environment, such as java.lang.Thread.
The example below demonstrates how to execute two tasks in parallel and wait for their completion before continuing the flow.
This example demonstrates an advanced integration scenario in which the interceptor performs chained calls to external services and manually handles HTTP (302) redirects.
In this example, there is a backend which, in case of errors, returns a stacktrace in HTML or simple text formats.
Instead, we want to set an appropriate response to the client.
We will execute the script at the after-response stage.
Another option would be returning a standard error message inside a JSON.
To do that, execute the code below at the after-response stage:
In some cases, we have APIs that transfer confidential data between the backend and the client (such as credit card numbers) and we don't want to expose these data, not even to system administrators that might use the API Manager to look into problems.
In this example, we will use a script that runs at the before-metric point to mask these fields.
NOTEThe request and the response are not modified by the script below; only the copies of these objects, sent to the Manager for storage and analysis, are affected. The backend keeps on receiving the credit card number that was sent by the client, and the client keeps on receiving the number in the response.
This is a script to obtain a token from a cookie. In the example below, we have a request that sends the access token as a cookie β that is, among the other cookies sent to the server. The HTTP request is as follows:
Note that there are three tokens in the Cookie header, and we want the API Gateway's processing to treat the request as if the abcdef AccessToken had been sent in an access_token header.
We will execute the script in the request flow, since it is during validation that the tokens will be extracted and validated.
This is a script to handle billing.
Observations:
billingValue works with Double precision, so it might be rounded or lose accuracy in decimal places.We use cookies to enhance your experience on our site. By continuing to browse, you agree to our use of cookies.Learn more