njs request transformation
Transform data without granting trust
A transformation converts an input into a predictable output. In this example a synthetic display preference is restricted to two known values; missing, repeated or unknown input uses compact. The output is never a role, permission or destination. Separating pure logic from Nginx objects makes the logic testable without a running proxy. r.args is request data and must be treated as untrusted.
function viewName(value) { return value === "expanded" ? "expanded" : "compact";}function view(r) { return viewName(r.args.view); }export default { view };Use js_set for a derived variable
The partial HTTP configuration below computes a variable when it is needed. A js_set function must finish synchronously; it should not wait for a fetch or timer. The ordinary return value becomes the variable value. With the previous module saved as views.js, /view?view=expanded yields expanded and /view?view=unknown yields compact. Do not rely on variable evaluation as a guaranteed once-per-request side effect. Avoid mutable module globals, especially when engine contexts can be reused.
js_import views from views.js;js_set $display_view views.view;server { listen 127.0.0.1:19439; location = /view { return 200 "$display_view\n"; }}Generate a response with js_content
A content handler can set response headers before completing the response. The example uses only an allowlisted display value and a structured serializer. The request /summary?view=expanded returns JSON containing view: expanded. Invalid input gets the compact fallback, not an error and not a permission grant. An asynchronous content handler may await a fixed internal subrequest when the selected module supports it; it must handle status and failure, bound response size and avoid client-selected URLs. Do not use network requests for this simple operation.
function summary(r) { const view = r.args.view === "expanded" ? "expanded" : "compact"; r.headersOut["Content-Type"] = "application/json"; r.return(200, JSON.stringify({ view }) + "\n");}// Add summary to the module default export; bind with js_content.Filters process response data in chunks
Header filters modify metadata; body filters receive successive chunks, not necessarily a complete message or a complete UTF-8 character. This toy filter is intended only for a known uncompressed ASCII fixture: every lowercase ASCII letter is converted to uppercase, and final-buffer flags are preserved. For general binary payloads use buffer mode and a byte-aware algorithm. When transforming representation bytes, review Content-Length, ETag, range handling, encoding and cache semantics; the companion lab deliberately clears validators and disables ranges for its fixture. Header and body filters are synchronous, not places to wait for external calls.
function headers(r) { delete r.headersOut["Content-Length"]; delete r.headersOut["ETag"]; delete r.headersOut["Last-Modified"];}function upper(r, data, flags) { r.sendBuffer(data.replace(/[a-z]/g, c => c.toUpperCase()), flags);}// Export headers and upper, then bind js_header_filter and js_body_filter.Practice and next steps
Predict the view for missing, repeated, expanded and unexpected values. Explain why filtering a split token is not the same as filtering the entire response. Next: nginx-extension-boundaries.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
njs request transformation
Describe a small trusted data transformation
What does viewName("expanded") return?
What happens to an array of repeated display values?
Which operation fits js_set?
Why can a body filter not assume one chunk is a whole document?
What must be reconsidered after modifying representation bytes?