You wrote the map block. Then a second map that reads the first one. Then an if inside a location, which the nginx documentation itself calls evil, and it still cannot verify an HMAC or parse a claim out of a header. njs is nginx’s own JavaScript module: a small engine compiled into the server that runs your code inside the worker process, on the same event loop as everything else, with no extra hop and no sidecar. This guide installs it, separates the three directives that actually matter (js_import, js_set, js_content), walks through a handler that rejects an unsigned request with a 401 before it ever touches your application and computes a tenant-aware cache key on the way through, and is specific about the work njs will never do for you.
What you’ll accomplish
- Install and load the njs module on Debian/Ubuntu or from the nginx.org packages, and confirm nginx actually sees the new directives.
- Know which point in request handling each of
js_var,js_set, andjs_contenttouches, and why that dictates where your logic can live. - Ship a handler that verifies an HMAC-signed header, returns
401from nginx itself, and hands valid requests onward withr.internalRedirect(). - Compute a
proxy_cache_keyfrom decoded token claims usingjs_set. - Recognise the blocking operations that stall a whole worker, and the class of logic that belongs in your application instead.
Prerequisites
- nginx 1.22 or newer with njs 0.8.x. Most of this works on older njs, but
js_varneeds 0.5.3 andjs_shared_dict_zoneneeds 0.8.0. Pin down your version before you copy config from a blog post written against a different one. - Root or
sudo, and the ability to reload nginx. - A real upstream to protect. This example assumes an HTTP application on
127.0.0.1:8080. - Package names differ by distro, and this is where most people stall. From the official nginx.org repository (deb and rpm alike) the package is
nginx-module-njs, and it does not load itself — you add aload_moduleline by hand. From the Debian or Ubuntu archive the package islibnginx-mod-http-js, and it drops a snippet into/etc/nginx/modules-enabled/that loads the module for you. Other distributions package it separately too; search your package index fornjsorhttp-jsbefore you assume you have to compile. If you build nginx yourself, njs is a dynamic module built from the njs source tree with--add-dynamic-module=. - You do not need Node.js, npm, or a JavaScript toolchain on the box. If your plan involves
npm install, stop reading now — see the limits section.
How it works
njs is not a template preprocessor and it is not a plugin sandbox that runs “somewhere”. It is a module that registers handlers at specific points in nginx’s request handling, and each directive registers at a different point. That is the whole mental model, and getting it wrong is what makes njs feel unpredictable.
js_content installs a content handler for a location. Your function owns the response from that point: nothing else in the location will produce a body, and the request stays open until you call r.return(), r.finish(), or r.internalRedirect(). It may be async.
js_set binds a JavaScript function to an nginx variable. It is evaluated lazily — the function does not run when the request arrives, it runs the first time something actually reads $your_var, and by default the result is cached for the rest of the request. That laziness is a feature (a variable used only inside proxy_cache_key costs nothing on requests that never reach the cache) and a trap (the function must return a value synchronously; it cannot await anything).
js_var $name; simply declares a variable that njs is allowed to write to. Ordinary nginx variables are read-only from JavaScript; js_var is how you create a scratch slot to pass a decoded claim from your handler to a proxy_set_header later.
One thing worth pinning down, because most write-ups predate it: the HTTP module went almost all of njs’s life without an access-phase directive. js_access, which sets an njs function as a handler in the access phase, only arrived in njs 0.9.9 (May 2026). Distribution packages lag a long way behind that, so treat it as unavailable unless you are installing njs from nginx.org’s own repository. Two options work on any build. You can point auth_request at an internal location whose content handler is njs, which costs you a real subrequest. Or you can make js_content the entry point for the location, validate, and then r.internalRedirect() to a named location that does the proxy_pass. The second is cheaper, works everywhere, and is what this guide uses.
The request object you get is deliberately small: r.method, r.uri, r.args, r.headersIn, r.headersOut, r.variables, r.status, r.requestText. Your levers are r.return(code, body), r.internalRedirect(uri), r.subrequest(uri, options), and the log functions r.log(), r.warn(), r.error(). That is nearly the whole surface, and it is enough.
Step-by-step
1. Install the module. On Debian or Ubuntu, from the distribution archive:
sudo apt-get install libnginx-mod-http-js
ls /etc/nginx/modules-enabled/
You should see a snippet whose name contains http-js. On a host using the nginx.org repository instead:
sudo apt-get install nginx-module-njs # or: sudo dnf install nginx-module-njs
ls /etc/nginx/modules/ngx_http_js_module.so
The ls must print the path. If it does not, the package did not install the HTTP module and you are probably looking at the stream-only variant.
2. Load it, if your package did not. Only for the nginx.org packages. This line goes in the main context of /etc/nginx/nginx.conf — above events, not inside http:
load_module modules/ngx_http_js_module.so;
While you are in the main context, declare the environment variable that will carry your signing key. nginx scrubs its environment on start, so process.env in njs sees nothing unless you list the name here:
env TOKEN_SECRET;
3. Write the module. Create /etc/nginx/njs/edge.js. This verifies a token of the form tenant:expiry.hexsignature, where the signature is an HMAC-SHA256 of everything before the last dot:
import crypto from 'crypto';
const SECRET = process.env.TOKEN_SECRET;
function verify(token) {
if (typeof token !== 'string') { return null; }
const dot = token.lastIndexOf('.');
if (dot < 1) { return null; }
const payload = token.substring(0, dot);
const given = token.substring(dot + 1);
const expected = crypto.createHmac('sha256', SECRET)
.update(payload)
.digest('hex');
if (given.length !== expected.length) { return null; }
// Compare every byte; do not bail out on the first mismatch.
let diff = 0;
for (let i = 0; i < expected.length; i++) {
diff |= given.charCodeAt(i) ^ expected.charCodeAt(i);
}
if (diff !== 0) { return null; }
const parts = payload.split(':');
if (parts.length !== 2) { return null; }
const expiry = Number(parts[1]);
if (!expiry || expiry * 1000 < Date.now()) { return null; }
return { tenant: parts[0], expiry: expiry };
}
function gate(r) {
const claims = verify(r.headersIn['X-Api-Token']);
if (claims === null) {
r.error('edge: rejected ' + r.method + ' ' + r.uri);
r.headersOut['Content-Type'] = 'application/json';
r.return(401, JSON.stringify({ error: 'invalid_token' }));
return;
}
r.variables.tenant = claims.tenant;
r.internalRedirect('@app');
}
function cacheKey(r) {
// Lazy: only runs when proxy_cache_key is read.
const tenant = r.variables.tenant || 'anon';
const plan = r.args.plan || 'default';
return tenant + '|' + plan + '|' + r.uri;
}
export default { gate, cacheKey };
4. Wire the directives. In the http context, then the server block:
js_path "/etc/nginx/njs/";
js_import edge from edge.js;
js_var $tenant;
js_set $api_cache_key edge.cacheKey;
proxy_cache_path /var/cache/nginx/api levels=1:2 keys_zone=api_cache:10m
max_size=1g inactive=10m;
upstream app { server 127.0.0.1:8080; }
server {
listen 443 ssl;
server_name api.example.com;
location /v1/ {
js_content edge.gate;
}
location @app {
proxy_cache api_cache;
proxy_cache_key $api_cache_key;
proxy_cache_valid 200 60s;
add_header X-Cache-Status $upstream_cache_status always;
proxy_set_header X-Tenant $tenant;
proxy_pass http://app;
}
}
Two requests that differ only by tenant now get separate cache entries, because the key is computed from a claim the client cannot forge. If the caching side of this is new to you, the mechanics are covered in nginx proxy caching for an upstream.
5. Give the secret to nginx. With systemd, an override file rather than a shell export, so it survives a reboot:
sudo systemctl edit nginx
Add, then reload the unit:
[Service]
Environment=TOKEN_SECRET=replace-with-a-long-random-string
6. Understand the async rule before you write anything bigger. njs runs on the worker’s event loop. There is no thread pool behind it. A synchronous HTTP call, a blocking fs read, or a tight loop over a large body does not slow down one request — it freezes every connection that worker is holding. Anything that talks to the outside world must be a promise:
async function gateWithLookup(r) {
const reply = await r.subrequest('/_introspect', { args: 'token=' + r.args.t });
if (reply.status !== 200) {
r.return(401);
return;
}
r.internalRedirect('@app');
}
r.subrequest() returns a promise when you omit the callback, and /_introspect must be an internal location that proxies wherever the check lives. This works in a js_content handler because it can be async. It will not work in a js_set handler — that one has to return a string right now, or the variable ends up empty.
7. Reload. njs modules are read at configuration load, once per worker:
sudo nginx -t && sudo systemctl reload nginx
Expect syntax is ok and test is successful. Editing edge.js without a reload changes nothing.
Validate it works
Mint a token with the same secret and check both outcomes. The unsigned case first:
curl -s -o /dev/null -w '%{http_code}\n' https://api.example.com/v1/orders
That must print 401. Now a valid one:
SECRET='replace-with-a-long-random-string'
PAYLOAD="acme:$(( $(date +%s) + 3600 ))"
SIG=$(printf '%s' "$PAYLOAD" | openssl dgst -sha256 -hmac "$SECRET" -hex | awk '{print $NF}')
curl -i -H "X-Api-Token: ${PAYLOAD}.${SIG}" https://api.example.com/v1/orders
You want a 200, plus an X-Cache-Status header — MISS on the first call and HIT on an immediate repeat. Tamper with one character of $SIG and re-run: you should get 401 again, and a matching edge: rejected GET /v1/orders line in the error log:
sudo tail -n 20 /var/log/nginx/error.log
To prove the cache key really is tenant-scoped, mint a second token for a different tenant and request the same URI. The first call for that tenant must be a MISS even though the previous tenant’s copy is warm.
Troubleshooting
unknown directive "js_import" on nginx -t. The module is not loaded. On nginx.org packages, check that load_module sits in the main context of nginx.conf and not inside http. On Debian, check that include /etc/nginx/modules-enabled/*.conf; is still present near the top of nginx.conf — it is easy to lose when someone rewrites the file from a template.
open() "/etc/nginx/edge.js" failed. js_import resolves relative to the nginx prefix unless js_path says otherwise, and js_path needs its trailing slash. Set js_path "/etc/nginx/njs/"; before the js_import line, or give js_import an absolute path.
A 500 with js exception in the error log. Read the line — njs reports the message and usually the function. The classic one here is a TypeError inside createHmac because SECRET is undefined: you added Environment= to systemd but forgot env TOKEN_SECRET; in nginx.conf, so nginx never passed the variable through.
$api_cache_key is empty and everything shares one cache entry. Either the js_set function threw (check the error log) or it returned a non-string. It can also be a caching surprise: js_set results are cached per request, so if $api_cache_key was read before r.variables.tenant was assigned, it captured anon. Keep the assignment in the handler that runs first.
rewrite or internal redirection cycle. Your r.internalRedirect() target resolves back into a location that also runs js_content edge.gate. Named locations (@app) avoid this because a prefix location cannot accidentally match them.
When this is the wrong approach
njs is a scalpel for edge concerns: signature checks, header normalisation, key derivation, routing decisions that depend on request content. It is a bad home for anything else.
Business rules belong in the application. The moment your handler needs a database, a user record, or a permission model, you are writing an application inside a proxy that has no test harness, no debugger, no dependency management, and whose only failure output is a line in the error log. The 40 lines above are near the ceiling of what stays maintainable.
njs is not Node.js and never intends to be. There is no npm, no node: module namespace, and the standard library is njs’s own small set — crypto, querystring, buffer, fs and a few more. fs exists but its calls block the worker, so it is for start-up reads, not per-request work. Each worker process gets its own isolate with no shared state, so a counter in a module-level variable counts only what that one worker saw; js_shared_dict_zone is the only cross-worker channel, and it holds strings and numbers, not objects.
Some jobs already have a directive, and the directive is faster and better tested. Rate limiting is limit_req. Static header rewriting is add_header and map. Basic auth is auth_basic. Reach for njs when a map genuinely cannot express the decision, not when it merely takes three of them.
And if you are earlier than all of this — still choosing what sits at the edge — the trade-offs are worth understanding first; see choosing between Caddy and nginx. Once you commit to njs you have committed to nginx, because nothing else runs it.
Both the njs reference and the ngx_http_js_module directive list are worth keeping open; the API surface changes between minor njs releases more than nginx directives usually do.
If this is the kind of work you’d rather never own again, it’s the daily job of Managed Cloud Ops — book an infrastructure review.