enable_jsvm
to true
in your tyk.conf
file.
request
: an object describing the API request that invoked the middleware
session
: the key session object provided by the client when making the API request
config
: an object containing fields from the API definition
TykJS
namespace into the JSVM, which can be used to initialise a new middleware component. The JS for each middleware component should be in its own *.js
file.
You create a middleware object by calling the TykJS.TykMiddleware.NewMiddleware({})
constructor with an empty object and then initialising it with your function using the NewProcessRequest()
closure syntax. This is where you expose the external data objects to your custom function.
request
and session.meta_data
objects in the ReturnData
as follows:
ReturnOverrides
in the request
object, as described here.
responseObject
. This is crucial as it determines the HTTP response that will be sent back to the client. The structure of this object is defined to ensure that the virtual endpoint can communicate the necessary response details back to the Tyk Gateway, which then forwards it to the client.
The responseObject
has the following structure:
code
: an integer representing the HTTP status code of the responseheaders
: an object containing key-value pairs representing the HTTP headers of the responsebody
: a string that represents the body of the response which can be plain text, JSON, or XML, depending on what your API client expects to receiveresponseObject
together with the session.meta_data
as parameters in a call to TykJsResponse
as follows:
request
objectrequest
object provides a set of arrays that describe the API request. These can be manipulated and, when changed, will affect the request as it passes through the middleware pipeline. For virtual endpoints the request object has a different structure.
The structure of the request
object is:
Headers
: this is an object of string arrays, and represents the current state of the request header; this object cannot be modified directly, but can be used to read header dataSetHeaders
: this is a key-value map that will be set in the header when the middleware returns the object; existing headers will be overwritten and new headers will be addedDeleteHeaders
: any header name that is in this list will be deleted from the outgoing request; note that DeleteHeaders
happens before SetHeaders
Body
: this represents the body of the request, if you modify this field it will overwrite the requestURL
: this represents the path portion of the outbound URL, you can modify this to redirect a URL to a different upstream pathAddParams
: you can add parameters to your request here, for example internal data headers that are only relevant to your network setupDeleteParams
: these parameters will be removed from the request as they pass through the middleware; note DeleteParams
happens before AddParams
ReturnOverrides
: values stored here are used to stop or halt middleware execution and return an error codeIgnoreBody
: if this parameter is set to true
, the original request body will be used; if set to false
the Body
field will be used (false
is the default behavior)Method
: contains the HTTP method (GET
, POST
, etc.)RequestURI
: contains the request URI, including the query string, e.g. /path?key=value
Scheme
: contains the URL scheme, e.g. http
, https
ReturnOverrides
request.ReturnOverrides
then Tyk will terminate the request and provide a response to the client when the function completes. The request will not be proxied to the upstream.
The response will use the parameters configured in ReturnOverrides
:
ResponseCode
ResponseBody
ResponseHeaders
HTTP 403 Access Denied
with the custom header "X-Error":"the-condition"
:
request
objectrequest
object is:
Body
: HTTP request body, e.g. ""
Headers
: HTTP request headers, e.g. "Accept": ["*/*"]
Params
: Decoded query and form parameters, e.g. { "confirm": ["true"], "userId": ["123"] }
Scheme
: The scheme of the URL ( e.g. http
or https
)URL
: The full URL of the request, e.g /vendpoint/anything?user_id=123\u0026confirm=true
Params
field of the request object.Repeated parameter assignments are appended to the corresponding array. For example, a request against /vendpoint/anything?user_id[]=123&user_id[]=234
would result in a Javascript request object similar to that shown below:session
objectmeta_data
field, the session object itself cannot be directly edited as it is crucial to the correct functioning of Tyk.
session
data will only be available to the JS function if enabled in the middleware configuration.session
objectmeta_data
key/value field that is written back to the session store (and can be retrieved by the middleware down the line) - this data is permanent, and can also be retrieved by the REST API from outside of Tyk using the /tyk/keys/
method.
config
objectAPIID
: the unique identifier for the APIOrgID
: the organization identifierconfig_data
: custom attributes defined in the API descriptiondata
object in the x-tyk-api-gateway.middleware.global.pluginConfig
section of the API definition, for example:
config_data
object in the root of the API definition:
request
, session
, config
) are made available to the function and the two objects that are returned from the function (in case the external objects need to be updated).
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.
This list is regularly revised and any new suggestions should be made in our Github issue tracker.
Below is the list of functions currently provided by Tyk.
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 in your Tyk installation middleware
directory for more details.rawlog(string)
: Calling rawlog("this message")
will cause Tyk to log the string to Tyk’s default logger output without any additional formatting, like adding prefix or date. This function can be used if you want to have own log format, and parse it later with custom tooling.b64enc
- Encode string to base64b64dec
- Decode base64 stringTykBatchRequest
this function is similar to TykMakeHttpRequest
but makes use of Tyk’s batch request feature.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:Domain
property.TykGetKeyData
and TykSetKeyData
:
TykGetKeyData(api_key, api_id)
: Use this method to retrieve a session object for the key and the API provided:
TykSetKeyData(api_key, api_id)
: Use this method to write data back into the Tyk session store:
middleware/
and event_handlers/
folders.
API Id
being loaded, and then load the pre
and post
middleware from the respective directories.
_with_session
to the filename.
enable_jsvm
to true
in your tyk.conf
file.
{API Id}
being loaded, and then load the pre
and post
middleware from the respective folders.
_with_session
to the filename.
enable_jsvm
to true
in your tyk.conf
file.
enable_jsvm
to true
in your tyk.conf
file.
Adding the middleware plugin is as simple as adding it to your definition file in the middleware sections:
pre
: Defines a list of custom middleware objects to run in order from top to bottom. That will be executed before any authentication information is extracted from the header or parameter list of the request. Use middleware in this section to pre-process a request before feeding it through the Tyk middleware.
pre[].name
: The name of the middleware object to call. This is case sensitive, and must match the name of the middleware object that was created, so in our example - we created sampleMiddleware
by calling:
var sampleMiddleware = new TykJS.TykMiddleware.NewMiddleware({});
pre[].path
: The path to the middleware component, this will be loaded into the JSVM when the API is initialised. This means that if you reload an API configuration, the middleware will also be re-loaded. You can hot-swap middleware on reload with no service interruption.
pre[].require_session
: Irrelevant for pre-processor middleware, since no auth data has been extracted by the authentication middleware, it cannot be made available to the middleware.
post
: Defines a list of custom middleware objects to run in order from top to bottom. That will be executed after the authentication, validation, throttling, and quota-limiting middleware has been executed, just before the request is proxied upstream. Use middleware in this section to post-process a request before sending it to your upstream API.
post[].name
: The name of the middleware object to call. This is case sensitive, and must match the name of the middleware object that was created, so in our example - we created sampleMiddleware
by calling:
var sampleMiddleware = new TykJS.TykMiddleware.NewMiddleware({});
post[].path
: The path to the middleware component, this will be loaded into the JSVM when the API is initialised. This means that if you reload an API configuration, the middleware will also be re-loaded. You can hot-swap middleware on reload with no service interruption.
post[].require_session
: Defaults to false
, if you require access to the session object, it will be supplied as a session
variable to your middleware processor function.
tyk.conf
at the root level:
Turn on JSVM interpreter to allow Tyk to run JavaScript plugins.
waf.js
into the middleware
directory:
docker exec
403
.
Now we try through Tyk.