Sample PRE middleware and open API


#1

Hi -
Using Tyk 2.2, I am trying to get pre-request middleware to work. This is on a simple open API using Community Edition with file-based configuration.

The sample PRE middleware installs and initializes correctly, but when the API is actually called, I get:
level=error msg="Failed to decode middleware request data on return from VM: invalid character 'u' looking for beginning of value"

This is the sample I’m using:

// ---- Sample middleware creation by end-user -----
var samplePreProcessMiddleware = new TykJS.TykMiddleware.NewMiddleware({});

samplePreProcessMiddleware.NewProcessRequest(function(request, session) {
    // You can log to Tyk console output by calloing the built-in log() function:
    log("Running sample  PRE PROCESSOR JSVM middleware")

    // Set and Delete headers in an outbound request
    request.SetHeaders["User-Agent"] = "Tyk-Custom-JSVM-Middleware";
    //request.DeleteHeaders.push("Authorization");

    // Change the outbound URL Path (only fragment, domain is fixed)
    // request.URL = "/get";

    // Add or delete request parmeters, these are encoded for the request as needed.
    request.AddParams["test_param"] = "My Teapot";
    request.DeleteParams.push("delete_me");

    // Override the body:
    request.Body = "New Request body"

    // You MUST return both the request and session metadata
    return samplePreProcessMiddleware.ReturnData(request, {});
});

// Ensure init with a post-declaration log message
log("Sample PRE middleware initialised");

Thanks for your help.


#2

Hi Craig,

The documentation regarding Middleware Scripting states that PRE instances shouldn’t have access to the session object as this won’t have been created yet. Have you tried removing the session parameter from your function?

https://tyk.io/docs/tyk-v2-2-documentation-components/middleware-scripting/

Regards,

Jess @ Tyk


#3

Found the issue and what may be a bit of a bug.
The API is loaded via a JSON file in the app path -

  "custom_middleware": {
    "pre": [
        {
            "name": "sampleMiddleware",
            "path": "middleware/sample.js",
            "require_session": false
        }
    ],
    "post": null,
    "response": null
  },

The name is not the same as the function name. Changing that fixes the issue.

The bug is that it even loaded and invoked the middleware if it wasn’t the one in the configuration. Or - for that matter - if I change the declaration to remove the session object, it doesn’t emit any initialised message - but still does load and invoke it when the API is called.

Might be an area to add some additional checking to trap when things aren’t lining up right.


#4

+1

I ran into same issue as well and wasted lot of time before stumbling on this post.