I am trying to add a custom response header to the response from an upstream server in Nginx based on the response body.
For simplicity, let this custom header be the SHA1 hash of the response body. To accomplish this, I'm attempting to use the njs scripting module for Nginx.
I've referred to the examples in the njs-examples repository. However, those examples treat the headers and body sections separately, and I'm struggling to combine them to achieve my goal.
Here is my current configuration:
# nginx.conf
load_module modules/ngx_http_js_module.so;
events {}
http {
js_path "/etc/nginx/njs/";
js_import main from hello.js;
# Configuration containing list of application servers
upstream app_servers {
server flask:5000;
}
server {
listen 80;
server_name localhost;
location / {
js_body_filter main.hello;
proxy_pass http://app_servers/;
}
}
}
# hello.js
function hello(r, data, flags) {
var val = data.length;
ngx.log(1, val);
r.headersOut["X-Hello"] = val;
r.sendBuffer(data, flags);
}
export default { hello };
However, when I send a request to my Nginx server, I don't see the X-Hello header in the response.
Is there a way to achieve my use case using njs scripting in Nginx? If not, what alternative approaches should I consider, such as implementing a custom Nginx module? Any suggestions or guidance on how to proceed would be greatly appreciated.
PS: I am running this setup on a Docker container with the official nginx image with some script for hot-reloading. If needed, I can share the Dockerfile and docker-compose.yml as well.
Answered by Liam Crilly on Nginx community slack.
nginx.confsnippetbody.jsTest