=encoding utf-8 =head1 NAME ngx_http_js_module - Module ngx_http_js_module =head1 The C module is used to implement location and variable handlers in L — a subset of the JavaScript language. Download and install instructions are available L. =head1 Example Configuration The example works since L<0.4.0|changes>. http { js_import http.js; js_set $foo http.foo; js_set $summary http.summary; js_set $hash http.hash; resolver 10.0.0.1; server { listen 8000; location / { add_header X-Foo $foo; js_content http.baz; } location = /summary { return 200 $summary; } location = /hello { js_content http.hello; } # since 0.7.0 location = /fetch { js_content http.fetch; js_fetch_trusted_certificate /path/to/ISRG_Root_X1.pem; } # since 0.7.0 location = /crypto { add_header Hash $hash; return 200; } } } The F file: function foo(r) { r.log("hello from foo() handler"); return "foo"; } function summary(r) { var a, s, h; s = "JS summary\n\n"; s += "Method: " + r.method + "\n"; s += "HTTP version: " + r.httpVersion + "\n"; s += "Host: " + r.headersIn.host + "\n"; s += "Remote Address: " + r.remoteAddress + "\n"; s += "URI: " + r.uri + "\n"; s += "Headers:\n"; for (h in r.headersIn) { s += " header '" + h + "' is '" + r.headersIn[h] + "'\n"; } s += "Args:\n"; for (a in r.args) { s += " arg '" + a + "' is '" + r.args[a] + "'\n"; } return s; } function baz(r) { r.status = 200; r.headersOut.foo = 1234; r.headersOut['Content-Type'] = "text/plain; charset=utf-8"; r.headersOut['Content-Length'] = 15; r.sendHeader(); r.send("nginx"); r.send("java"); r.send("script"); r.finish(); } function hello(r) { r.return(200, "Hello world!"); } // since 0.7.0 async function fetch(r) { let results = await Promise.all([ngx.fetch('https://nginx.org/'), ngx.fetch('https://nginx.org/en/')]); r.return(200, JSON.stringify(results, undefined, 4)); } // since 0.7.0 async function hash(r) { let hash = await crypto.subtle.digest('SHA-512', r.headersIn.host); r.setReturnValue(Buffer.from(hash).toString('hex')); } export default {foo, summary, baz, hello, fetch, hash}; =head1 Directives =head2 js_body_filter B js_body_filter I> E I> [I>=I> E I>]> B I B I B I This directive appeared in version 0.5.2. Sets an njs function as a response body filter. The filter function is called for each data chunk of a response body with the following arguments: =over =item C the L object =item C the incoming data chunk, may be a string or Buffer depending on the C value, by default is a string. Since L<0.8.5|changes>, the C value is implicitly converted to a valid UTF-8 string by default. For binary data, the C value should be set to C. =item C an object with the following properties: =over =item C a boolean value, true if data is a last buffer. =back =back The filter function can pass its own modified version of the input data chunk to the next body filter by calling L|reference>. For example, to transform all the lowercase letters in the response body: function filter(r, data, flags) { r.sendBuffer(data.toLowerCase(), flags); } To stop filtering (following data chunks will be passed to client without calling C), L|reference> can be used. If the filter function changes the length of the response body, then it is required to clear out the C response header (if any) in C to enforce chunked transfer encoding. B As the C handler returns its result immediately, it supports only synchronous operations. Thus, asynchronous operations such as L or L are not supported. B The directive can be specified inside the L block since L<0.7.7|changes>. =head2 js_content B js_content I> E I>> B I B I B I Sets an njs function as a location content handler. Since L<0.4.0|changes>, a module function can be referenced. B The directive can be specified inside the L block since L<0.7.7|changes>. =head2 js_context_reuse B js_context_reuse I>> B I<128> B I B I B I This directive appeared in version 0.8.6. Sets a maximum number of JS context to be reused for L. Each context is used for a single request. The finished context is put into a pool of reusable contexts. If the pool is full, the context is destroyed. =head2 js_engine B js_engine I E C> B I B I B I B I This directive appeared in version 0.8.6. Sets a L to be used for njs scripts. The C parameter sets the njs engine, also used by default. The C parameter sets the QuickJS engine. =head2 js_fetch_buffer_size B js_fetch_buffer_size I>> B I<16k> B I B I B I This directive appeared in version 0.7.4. Sets the I> of the buffer used for reading and writing with L. =head2 js_fetch_ciphers B js_fetch_ciphers I>> B I B I B I B I This directive appeared in version 0.7.0. Specifies the enabled ciphers for HTTPS requests with L. The ciphers are specified in the format understood by the OpenSSL library. The full list can be viewed using the “C” command. =head2 js_fetch_max_response_buffer_size B js_fetch_max_response_buffer_size I>> B I<1m> B I B I B I This directive appeared in version 0.7.4. Sets the maximum I> of the response received with L. =head2 js_fetch_protocols B js_fetch_protocols I< [C] [C] [C] [C]> B I B I B I B I This directive appeared in version 0.7.0. Enables the specified protocols for HTTPS requests with L. =head2 js_fetch_timeout B js_fetch_timeout I>> B I<60s> B I B I B I This directive appeared in version 0.7.4. Defines a timeout for reading and writing for L. The timeout is set only between two successive readEwrite operations, not for the whole response. If no data is transmitted within this time, the connection is closed. =head2 js_fetch_trusted_certificate B js_fetch_trusted_certificate I>> B I B I B I This directive appeared in version 0.7.0. Specifies a I> with trusted CA certificates in the PEM format used to L the HTTPS certificate with L. =head2 js_fetch_verify B js_fetch_verify I E C> B I B I B I B I This directive appeared in version 0.7.4. Enables or disables verification of the HTTPS server certificate with L. =head2 js_fetch_verify_depth B js_fetch_verify_depth I>> B I<100> B I B I B I This directive appeared in version 0.7.0. Sets the verification depth in the HTTPS server certificates chain with L. =head2 js_header_filter B js_header_filter I> E I>> B I B I B I This directive appeared in version 0.5.1. Sets an njs function as a response header filter. The directive allows changing arbitrary header fields of a response header. B As the C handler returns its result immediately, it supports only synchronous operations. Thus, asynchronous operations such as L or L are not supported. B The directive can be specified inside the L block since L<0.7.7|changes>. =head2 js_import B js_import I> E I>> B I B I B I This directive appeared in version 0.4.0. Imports a module that implements location and variable handlers in njs. The C is used as a namespace to access module functions. If the C is not specified, the module name will be used as a namespace. js_import http.js; Here, the module name C is used as a namespace while accessing exports. If the imported module exports C, C is used to refer to it. Several C directives can be specified. B The directive can be specified on the C and C level since L<0.7.7|changes>. =head2 js_include B js_include I>> B I Specifies a file that implements location and variable handlers in njs: nginx.conf: js_include http.js; location /version { js_content version; } http.js: function version(r) { r.return(200, njs.version); } The directive was made obsolete in version L<0.4.0|changes> and was removed in version L<0.7.1|changes>. The L directive should be used instead. =head2 js_path B js_path I< I>> B I B I B I This directive appeared in version 0.3.0. Sets an additional path for njs modules. B The directive can be specified on the C and C level since L<0.7.7|changes>. =head2 js_periodic B js_periodic I> E I> [C=I>] [C=I>] [C=I>]> B I This directive appeared in version 0.8.1. Specifies a content handler to run at regular interval. The handler receives a L as its first argument, it also has access to global objects such as L. The optional C parameter sets the interval between two consecutive runs, by default, 5 seconds. The optional C parameter sets the time within which the location content handler will be randomly delayed, by default, there is no delay. By default, the C is executed on worker process 0. The optional C parameter allows specifying particular worker processes where the location content handler should be executed. Each worker process set is represented by a bitmask of allowed worker processes. The C mask allows the handler to be executed in all worker processes. Example: example.conf: location @periodics { # to be run at 1 minute intervals in worker process 0 js_periodic main.handler interval=60s; # to be run at 1 minute intervals in all worker processes js_periodic main.handler interval=60s worker_affinity=all; # to be run at 1 minute intervals in worker processes 1 and 3 js_periodic main.handler interval=60s worker_affinity=0101; resolver 10.0.0.1; js_fetch_trusted_certificate /path/to/ISRG_Root_X1.pem; } example.js: async function handler(s) { let reply = await ngx.fetch('https://nginx.org/en/docs/njs/'); let body = await reply.text(); ngx.log(ngx.INFO, body); } =head2 js_preload_object B js_preload_object I> E I> from I>> B I B I B I This directive appeared in version 0.7.8. Preloads an L at configure time. The C is used as a name of the global variable though which the object is available in njs code. If the C is not specified, the file name will be used instead. js_preload_object map.json; Here, the C is used as a name while accessing the preloaded object. Several C directives can be specified. =head2 js_set B js_set I< I> I> E I> [C]> B I B I B I Sets an njs C for the specified C. Since L<0.4.0|changes>, a module function can be referenced. The function is called when the variable is referenced for the first time for a given request. The exact moment depends on a L at which the variable is referenced. This can be used to perform some logic not related to variable evaluation. For example, if the variable is referenced only in the L directive, its handler will not be executed until the log phase. This handler can be used to do some cleanup right before the request is freed. Since L<0.8.6|changes>, if an optional argument C is specified, the handler is called every time it is referenced. Due to current limitations of the L module, when a C variable is referenced by the L directive its handler should always return a fixed-length value. B As the C handler returns its result immediately, it supports only synchronous operations. Thus, asynchronous operations such as L or L are not supported. B The directive can be specified on the C and C level since L<0.7.7|changes>. =head2 js_shared_dict_zone B js_shared_dict_zone I< C=I>:I> [C=I>] [C=CEC] [C]> B I This directive appeared in version 0.8.0. Sets the I> and I> of the shared memory zone that keeps the key-value L shared between worker processes. By default the shared dictionary uses a string as a key and a value. The optional C parameter allows redefining the value type to number. The optional C parameter sets the time in milliseconds after which all shared dictionary entries are removed from the zone. If some entries require a different removal time, it can be set with the C argument of the L, L, and L methods (L<0.8.5|changes>). The optional C parameter removes the oldest key-value pair when the zone storage is exhausted. Example: example.conf: # Creates a 1Mb dictionary with string values, # removes key-value pairs after 60 seconds of inactivity: js_shared_dict_zone zone=foo:1M timeout=60s; # Creates a 512Kb dictionary with string values, # forcibly removes oldest key-value pairs when the zone is exhausted: js_shared_dict_zone zone=bar:512K timeout=30s evict; # Creates a 32Kb permanent dictionary with number values: js_shared_dict_zone zone=num:32k type=number; example.js: function get(r) { r.return(200, ngx.shared.foo.get(r.args.key)); } function set(r) { r.return(200, ngx.shared.foo.set(r.args.key, r.args.value)); } function del(r) { r.return(200, ngx.shared.bar.delete(r.args.key)); } function increment(r) { r.return(200, ngx.shared.num.incr(r.args.key, 2)); } =head2 js_var B js_var I> [I>]> B I B I B I This directive appeared in version 0.5.3. Declares a L variable. The value can contain text, variables, and their combination. The variable is not overwritten after a redirect unlike variables created with the L directive. B The directive can be specified on the C and C level since L<0.7.7|changes>. =head1 Request Argument Each HTTP njs handler receives one argument, a request L.