Is is possible to cache in middleware script

Hello,

I am writing a middleware script to perform token exchange for all the incoming legacy requests. Making the token exchange requires an extra REST call that I am able to do using method TykMakeHttpRequest(…). However most of these requests could be avoided if the middleware script could cache the already exchanged tokens. It seems to me that this is not possible. It looks like that all the changes done to any variable in the middleware script are reset after the request processing is completed. So is there any way to implement caching in the middleware script.

-Antti Huokko

Not really, you could cache in-memory though if you create a hash outside of the JS function (effectively a global) and add to it - this could then be a local cache.

V2.3 is bringing a custom auth cache as a built in function for new plugins though (it’s a few months away)

Hello,

That is what I was planning to do but it seems that it is not possible to store any state during request processing.
The following code logs undefined no matter how many times I call the endpoint. Any idea why is that?

var cache = {}; var iamLoginMiddleware = new TykJS.TykMiddleware.NewMiddleware({}); iamLoginMiddleware.NewProcessRequest(function(request, session) { log(cache['mytest']); cache['mytest'] = 'Test Value'; return iamLoginMiddleware.ReturnData(request, {}); });

Ah, yes I see.

Tyk will “fork” (deepcopy) the environment that the JS runs in so as to stop race conditions (multi-map access) in the interpreter, so this is why it might fail, since it never merges back. You’ll need an external cache (or wait for v2.3 where you can just save to redis).

Hello,

The new version sounds very promising. Is there some feature list of the new features that will be included in v2.3?

-Antti

Hi huokko,

Yes, you can take a look at Tyk Gateway Roadmap on our Trello board here

Kos,

Tyk Support Team