Send Docs Feedback

JavaScript policy

What

This policy lets you add custom JavaScript code that executes within the context of an API proxy flow. In your custom JavaScript code, you can use the objects, methods, and properties of the Apigee Edge JavaScript object model

Where

You can attach this policy to execute custom JavaScript code at any location in the API proxy flow.

ProxyEndpoint TargetEndpoint
    PreFlow Flow PostFlow PreFlow Flow PostFlow    
Request    
    Response
    PostFlow Flow PreFlow PostFlow Flow PreFlow    

About

There are many use cases for the JavaScript policy. For example, you can get and set flow variables, execute custom logic and perform fault handling, extract data from requests or responses, dynamically edit the backend target URL, and much more. This policy allows you to implement custom behavior that is not covered by any other standard Edge policies. In fact, you can use a JavaScript policy to achieve many of the same behaviors implemented by other policies, like AssignMessage and ExtractVariable.

Basically, the JavaScript policy specifies the name of the JavaScript source file to execute when the step to which the policy is attached executes. The source file is always stored in a standard location within the proxy bundle: apiproxy/resources/jsc. Or, you can also store the source code in a resource file at the environment or organization level. For instructions, see Resource files. You can also upload your JavaScript through the management UI proxy editor.

JavaScript source files must always have a .js extension.

Samples

Here's a common use case: extracting data from a request body, storing it in a flow variable, and using that flow variable elsewhere in the proxy flow. Let's say you have a weather app where the user enters their zip code in an HTML form and submits it. You want the API proxy to extract the form data and dynamically add it to the URL used to call the backend service. How would you do this in a JavsScript policy?

Note: If you want to try out this example, we assume you've created a new proxy in the proxy editor. When you create it, just give it a backend service URL of: http://www.example.com. For this example, we're going to rewrite the backend URL dynamically. If you don't know how to create a new proxy, refer to the getting started tutorial. .

 

if (context.flow=="PROXY_REQ_FLOW") {
     var woeid = context.getVariable("request.formparam.woeid");
     context.setVariable("location.woeid", woeid);
}


if (context.flow=="TARGET_REQ_FLOW") {
     context.setVariable("request.verb", "GET");
     var woeid = context.getVariable("location.woeid");
     var url = "http://weather.yahooapis.com/forecastrss?"
     context.setVariable("target.url", url + "w=" + woeid);
}

  1. In Edge UI, open the proxy that you created in the proxy editor.
  2. Select the Develop tab.
  3. From the New menu, select New Script.
  4. In the dialog, select JavaScript and give the script a name, like js-example.
  5. Paste the following code in the code editor and save the proxy. The important thing to notice is the context object. This object is available to the JavaScript code anywhere in the proxy flow. It's used to obtain flow-specific constants, to call useful get/set methods, and for more operations. This object part is of Edge's JavaScript Object Model. Note, too, that the target.url flow variable is a built-in, read/write variable that is accessible in the Target Request flow. When we set that variable with the "weather" API URL, Edge makes its backend call to that URL. We've essentially rewritten the original target URL, which was whatever you specified when you created the proxy (e.g., http://www.example.com).
  6. From the New Policy menu, select JavaScript.
  7. Give the policy a name, like target-rewrite. Accept the defaults, and save the policy.
  8. If you select the Proxy Endpoint Preflow in the Navigator, you'll see that the policy was added to that flow.
  9. In the Navigator, select the Target Endpoint PreFlow icon.
  10. From the Navigator, drag the JavaScript policy onto the Request side of the Target Endpoint in the flow editor.
  11. Save.
  12. Call the API like this, substituting your correct org name and proxy name as appropriate:
curl -i -H 'Content-Type: application/x-www-form-urlencoded' -X POST -d 'woeid=12797282' http://myorg-test.apigee.net/js-example

One final thing, let's take a look at the XML definition for the JavaScript policy used in this example. The important thing to note is that the <ResourceURL> element is used to speicfy the JavaScript source file to execute. This same pattern is used for any JavaScript source file: jsc://filename.js. If you're JavaScript code requires includes, you can use one or more <IncludeURL> elements to do that, as described later in this reference.

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Javascript async="false" continueOnError="false" enabled="true" timeLimit="200" name="target-rewrite">
    <DisplayName>target-rewrite</DisplayName>
    <Properties/>
    <ResourceURL>jsc://js-example.js</ResourceURL>
</Javascript>
 

Attributes

<Javascript async="false" continueOnError="false" enabled="true" timeLimit="200" 
        name="JavaScript-1">
Attribute Description Default Presence
async

Set to true to specify that the policy should be run in a thread pool different than the pool servicing the request/response flow. Default is false.

Note: This setting is only used for for internal optimization.

false Optional
continueOnError

Most policies are expected to return an error when a failure occurs. By setting this attribute to true, Flow execution continues on failure.

false Optional
enabled Determines whether a policy is enforced or not. If set to false, a policy is 'turned off', and not enforced (even though the policy remains attached to a Flow). true Optional
timeLimit

Specifies the maximum time (in milliseconds) that the script is permitted to execute.

Note: For free trial accounts, execution time is limited to 200 ms.

N/A Required
name

The internal name of the policy. This name is referenced in Step elements to attach the policy to a Flow.

Note: Characters you can use in the name are restricted to: A-Z0-9._\-$ %. The Management UI enforces additional restrictions, such as automatically removing characters that are not alphanumeric.

N/A Required

Elements

The element reference describes the elements and attributes of the JavaScript policy.

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <Javascript async="false" continueOnError="false" enabled="true" timeLimit="200" 
        name="JavaScript-1">
    <DisplayName>JavaScript 1</DisplayName>
    <ResourceURL>jsc://my-javascript-source-file</ResourceURL>
    <IncludeURL>jsc://a-javascript-library-file</IncludeURL>
</Javascript>

<DisplayName> element

A natural-language name that labels the policy in the management UI proxy editor. If omitted, the policy name attribute is used.

<DisplayName>JavaScript 1</DisplayName>
Default: Policy name attribute value.
Presence: Optional
Type: String

<ResourceURL> element

This element specifies the main JavaScript file that will execute in the API flow. This file must be stored under /apiproxy/resources/jsc in the API proxy bundle. Your code can use the objects, methods, and properties of the JavaScript object model.

<ResourceURL>jsc://my-javascript-source-file</ResourceURL>
Default: None
Presence: Required
Type: String

Example

See the Basic Example in the Samples section.

<IncludeURL>

Specifies a JavaScript library file to be loaded as dependency to the main JavaScript file specified with the ResourceURL element. Store JavaScript library files under under /apiproxy/resources/jsc in your API proxy. The scripts will be evaluated in the order in which they are listed in the policy. Your code can use the objects, methods, and properties of the JavaScript object model.

    <IncludeURL>jsc://a-javascript-library-file</IncludeURL>
Default: None
Presence: Optional
Type: String

Example

See the Basic Example in the Samples section.

Flow Variables

This policy does not populate any variables by default; however, you can set (and get) flow variables in your JavaScript code by calling methods on the context object. A typical pattern looks like this:

context.setVariable("response.header.X-Apigee-Target", context.getVariable("target.name"))

The context object is part of the Apigee Edge JavaScript Object Model. For more information, see JavaScript object model

Error codes

This policy defines the following error codes. For guidance on handling errors, see Fault handling.

The default format for error codes returned by policies is:

{
  "code" : " {ErrorCode} ",
  "message" : " {Error message} ",
  "contexts" : [ ]
}

The Javascript Policy type defines the following error codes:

Error Code Message
ScriptExecutionFailed Execution of {0} failed with error: {1}
ScriptExecutionFailedLineNumber Execution of {0} failed on line {2} with error: {1}
ScriptCompilationFailed Compilation of JavaScript {0} failed with error:{1}. Context {2}
NoResourceForURL Could not locate a resource with URL {0}
WrongResourceType Resource {0} is the wrong type. It is {1}: but Javascript steps use type jsc:

Schema

Each policy type is defined by an XML schema (.xsd). For reference, policy schemas are available on GitHub.

Related topics

Apigee Community articles

You can find these related articles on the Apigee Community:

Help or comments?

  • If something's not working: Ask the Apigee Community or see Apigee Support.
  • If something's wrong with the docs: Click Send Docs Feedback on this page.
    (Incorrect? Unclear? Broken link? Typo?)