A tiny Express response interceptor
Express-interceptor allows you to define a previous step before sending a response. This allows you to do anything you want with the response, such as processing, transforming, replacing, or logging it. Express-interceptor allows you to avoid calling
next() over and over. Further more, you can avoid managing nested scopes. Using a declarative API, it’s simple to use and maintain.
Some use cases include:
- Transpile custom elements into standard HTML elements.
- Transform JSX or compile less files on the fly.
- Store statistics about responses.
- Set response headers based on tags in the response body.
- Dynamically inject live-reload scripts to HTML.
Install the package
npm i --save express-interceptor
Define your interceptor
var express = ;var cheerio = ;var interceptor = ;var app = ;var finalParagraphInterceptor =// Add the interceptor middlewareapp;app;app;
You're defining an interceptor that will be executed whenever the response contains html as Content-Type. If this is true, it will append a child at the end of the body. In other words, it will transform the response:
"Hello world"From interceptor!
isInterceptable()(required): is a predicate function where you define a condition whether or not to intercept a response. Returning
truebuffers the request, and proceeds calling
intercept()as well as
afterSend(). Typically, you want to check for this condition in the
resobject in the definition of the middleware.
intercept(body, send)(required): Parse the body as an encoded string. After processing the body, call
send(newBody)with the content to be sent back to the client.
afterSend(oldBody, newBody): This method will be called after sending the response to the client – after the
done()callback in the
send()method is executed. This method would typically be used to cache something, log stats, fire a job, among other things.
Who is using it?
express-hijackresponse Different API, using callbacks with no top down structure, more obtrusive to HTTP internals.
tamper Similar functionality but different internals and API.
Words of advice
intercept method make calls to a database, or needs to make expensive transformations to the original response, you should take in account the time that will add to the response. You should define your
isInterceptable method carefully, checking the type of the response, or even the route that was fired by the request, also you may consider implementing a cache strategy to get faster responses.
If you face any issue, don't hesitate to submit it here.
Please check CONTRIBUTING.md.
This project adheres to the Open Code of Conduct. By participating, you are expected to honor this code.