js_body_filter

The `js_body_filter` directive allows you to filter and modify the response body of HTTP requests using JavaScript code in NGINX.

Syntaxjs_body_filter handler [options];
Defaultnone
Contextlocation, if in location, limit_except
Arguments1-2

Description

The js_body_filter directive is a feature of the NGINX JavaScript module that enables developers to manipulate the HTTP response body dynamically using JavaScript. This directive can be placed within specific contexts such as location, if in location, and limit_except. It accepts one or two arguments: the first argument specifies the JavaScript function to invoke, and an optional second argument allows for additional options or settings.

When js_body_filter is configured, NGINX invokes the specified JavaScript function during the response processing phase. The function receives input data about the request and allows for operation on the response body chunks before they are sent to the client. This offers the flexibility to add, modify, or transform details of the output based on complex logic written in JavaScript.

To utilize js_body_filter, you must ensure that your NGINX setup has the NGINX JavaScript module enabled. A typical use case might be to dynamically format JSON responses, filter out sensitive information, or append metadata to the response body, providing a powerful tool for custom response handling.

Config Example

location /api {
    js_body_filter my_js_function;
}

Ensure the JavaScript code does not block the event loop; otherwise, it can degrade NGINX performance.

Be cautious with buffer sizes, as too large response bodies may lead to memory issues.

Ensure the JavaScript function handles all potential input variations to avoid runtime errors.

← Back to all directives