Adding rate limiting
Hi, I'm trying to add rate limiting to Hapi via a plugin and there is something I could use help with.
The issue is that the rate limiting needs to have access to the routing information. The most apparent way to get this is to use the servers _router.route function. The obvious problem with this that _router is probably intended to be private. If any plugin is to access route data I would think it should use the same routing function as the rest of the system.
What do you guys think?
What info do you need? request.route gives you the active config.
Thanks for your reply, I tried to use that but it was a mostly empty object that didn't contain the route specific plugin settings. I am on an older version of Hapi (1.10).
what information you need access to?
I'm adding route specific rate limiting information to the route definition. For example this is a raw route object that is passed into the server.route method
{
method: 'GET',
path: '/catalog',
config: {
handler: handlers.catalog.get,
auth: {
mode: 'optional',
strategies: ['session']
},
plugins:{"cl-hapi-rate": {limit:5, bucketLength:60}}
},
}
In the config I added an arbitrary limit of 5 requests in 60 seconds for that route. Now when the server gets a request for that route the plugin will check the route plugins property for the presence of a rate limit.
The problem with the request.route object is that the request.route.plugins property is an empty object. I was able to get around this by passing along the server._router to the plugin and then using _router.route(request) to get the route definition which included the plugin info.
It will be empty in onRequest because route matching only happens after that. Use another extension point.
That was it. I got it working onPreAuth without _router. Thanks!
@cl-aaron I'd love to see your final version of the plugin. Please let us know if you publish it.
@cl-aaron: +1 to @calendee's request for the plugin
@cl-aaron Did you publish your plugin for rate limiting?
I can make it available but I wrote it for an older version of Hapi so it will need a bit of updating. It is a small plugin luckily.
That would be great. I can help updating it.
Alright here it is, https://www.npmjs.org/package/hapi-ratelimit . Very basic but it works.
Hi, sorry to bother you but I've also a problem with hapi + ratelimiter. Please take a look at http://stackoverflow.com/questions/33450671/hapijs-ratelimiter-plugin-dont-trigger-get-method. I don't understand why on earth the script doesn't enter in the limiter.get block.
Thanks in advance.
I've worked it out setting up the redis connection inside the plugin and not as option. I don't really understand why on earth it doesn't work with redis as option ! There is a simple first version.