JavaScript API

Overview

Embedded JavaScript interpreters offer the bare bones of a scripting language, but not necessarily the functions that you would expect, especially with JavaScript, where objects such as XMLHttpRequest() are a given. However, those interfaces are actually provided by the browser / DOM that the script engine are executing in. In a similar vein, we have included a series of functions to the JSVM for convenience and give the interpreter more capability.

log(string): Calling log("this message") will cause Tyk to log the string to Tyk’s default logger output in the form JSVM Log: this message as an INFO statement. This function is especially useful for debugging your scripts. It is recommended to put a log() call at the end of your middleware and event handler module definitions to indicate on load that they have been loaded successfully – see the example scripts supplied with Tyk for more details.

TykMakeHttpRequest(JSON.stringify(requestObject)): This method is used to make an HTTP request, requests are encoded as JSON for deserialisation in the min binary and translation to a system HTTP call. The request object has the following structure:

This method does not execute asynchronously, so execution will block until a response is received.

TykGetKeyData(api_key, api_id): Use this method to retrieve a session object for the key and the API provided:

// In an event handler, we can get the key idea from the event, and the API ID from the context variable.
var thisSession = JSON.parse(TykGetKeyData(event.EventMetaData.Key, context.APIID))
log("Expires: " + thisSession.expires)

TykSetKeyData(api_key, api_id):

Use this method to write data back into the Tyk session store:

// You can modify the object just like with the REST API
thisSession.expires = thisSession.expires + 1000;
// Use TykSetKeyData to set the key data back in the session store
TykSetKeyData(event.EventMetaData.Key, JSON.stringify(thisSession));

All of these methods are described in functional examples in the Tyk middleware/ and event_handlers/ folders.

Privacy Overview

This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.

You can adjust all of your cookie settings by navigating the tabs on the left hand side.