=encoding utf-8

=head1 NAME

ngx_stream_js_module - Module ngx_stream_js_module




=head1



The C<ngx_stream_js_module> module is used to implement
handlers in L<njs|index> —
a subset of the JavaScript language.





Download and install instructions are available
L<here|install>.




=head1 Example Configuration



The example works since
L<0.4.0|changes>.

    
    stream {
        js_import stream.js;
    
        js_set $bar stream.bar;
        js_set $req_line stream.req_line;
    
        server {
            listen 12345;
    
            js_preread stream.preread;
            return     $req_line;
        }
    
        server {
            listen 12346;
    
            js_access  stream.access;
            proxy_pass 127.0.0.1:8000;
            js_filter  stream.header_inject;
        }
    }
    
    http {
        server {
            listen 8000;
            location / {
                return 200 $http_foo\n;
            }
        }
    }







The F<stream.js> file:

    
    var line = '';
    
    function bar(s) {
        var v = s.variables;
        s.log("hello from bar() handler!");
        return "bar-var" + v.remote_port + "; pid=" + v.pid;
    }
    
    function preread(s) {
        s.on('upload', function (data, flags) {
            var n = data.indexOf('\n');
            if (n != -1) {
                line = data.substr(0, n);
                s.done();
            }
        });
    }
    
    function req_line(s) {
        return line;
    }
    
    // Read HTTP request line.
    // Collect bytes in 'req' until
    // request line is read.
    // Injects HTTP header into a client's request
    
    var my_header =  'Foo: foo';
    function header_inject(s) {
        var req = '';
        s.on('upload', function(data, flags) {
            req += data;
            var n = req.search('\n');
            if (n != -1) {
                var rest = req.substr(n + 1);
                req = req.substr(0, n + 1);
                s.send(req + my_header + '\r\n' + rest, flags);
                s.off('upload');
            }
        });
    }
    
    function access(s) {
        if (s.remoteAddress.match('^192.*')) {
            s.deny();
            return;
        }
    
        s.allow();
    }
    
    export default {bar, preread, req_line, header_inject, access};






=head1 Directives

=head2 js_access


B<syntax:> js_access I<I<C<function>> E<verbar> I<C<module.function>>>



B<context:> I<stream>


B<context:> I<server>





Sets an njs function which will be called at the
L<access|stream_processing> phase.
Since L<0.4.0|changes>,
a module function can be referenced.





The function is called once at the moment when the stream session reaches
the L<access|stream_processing> phase
for the first time.
The function is called with the following arguments:


=over


=item C<s>




the L<Stream Session|reference> object




=back







At this phase, it is possible to perform initialization
or register a callback with
the L<C<s.on()>|reference>
method
for each incoming data chunk until one of the following methods are called:
L<C<s.allow()>|reference>,
L<C<s.decline()>|reference>,
L<C<s.done()>|reference>.
As soon as one of these methods is called, the stream session processing
switches to the L<next phase|stream_processing>
and all current
L<C<s.on()>|reference>
callbacks are dropped.







=head2 js_context_reuse


B<syntax:> js_context_reuse I<I<C<number>>>


B<default:> I<128>


B<context:> I<stream>


B<context:> I<server>



This directive appeared in version 0.8.6.





Sets a maximum number of JS context to be reused for
L<QuickJS engine|engine>.
Each context is used for a single stream session.
The finished context is put into a pool of reusable contexts.
If the pool is full, the context is destroyed.







=head2 js_engine


B<syntax:> js_engine I<C<njs> E<verbar> C<qjs>>


B<default:> I<njs>


B<context:> I<stream>


B<context:> I<server>



This directive appeared in version 0.8.6.





Sets a L<JavaScript engine|engine>
to be used for njs scripts.
The C<njs> parameter sets the njs engine, also used by default.
The C<qjs> parameter sets the QuickJS engine.







=head2 js_fetch_buffer_size


B<syntax:> js_fetch_buffer_size I<I<C<size>>>


B<default:> I<16k>


B<context:> I<stream>


B<context:> I<server>



This directive appeared in version 0.7.4.





Sets the I<C<size>> of the buffer used for reading and writing
with L<Fetch API|reference>.







=head2 js_fetch_ciphers


B<syntax:> js_fetch_ciphers I<I<C<ciphers>>>


B<default:> I<HIGH:!aNULL:!MD5>


B<context:> I<stream>


B<context:> I<server>



This directive appeared in version 0.7.0.





Specifies the enabled ciphers for HTTPS connections
with L<Fetch API|reference>.
The ciphers are specified in the format understood by the OpenSSL library.





The full list can be viewed using the
“C<openssl ciphers>” command.







=head2 js_fetch_max_response_buffer_size


B<syntax:> js_fetch_max_response_buffer_size I<I<C<size>>>


B<default:> I<1m>


B<context:> I<stream>


B<context:> I<server>



This directive appeared in version 0.7.4.





Sets the maximum I<C<size>> of the response received
with L<Fetch API|reference>.







=head2 js_fetch_protocols


B<syntax:> js_fetch_protocols I<
    [C<TLSv1>]
    [C<TLSv1.1>]
    [C<TLSv1.2>]
    [C<TLSv1.3>]>


B<default:> I<TLSv1 TLSv1.1 TLSv1.2>


B<context:> I<stream>


B<context:> I<server>



This directive appeared in version 0.7.0.





Enables the specified protocols for HTTPS connections
with L<Fetch API|reference>.







=head2 js_fetch_timeout


B<syntax:> js_fetch_timeout I<I<C<time>>>


B<default:> I<60s>


B<context:> I<stream>


B<context:> I<server>



This directive appeared in version 0.7.4.





Defines a timeout for reading and writing
for L<Fetch API|reference>.
The timeout is set only between two successive readE<sol>write operations,
not for the whole response.
If no data is transmitted within this time, the connection is closed.







=head2 js_fetch_trusted_certificate


B<syntax:> js_fetch_trusted_certificate I<I<C<file>>>



B<context:> I<stream>


B<context:> I<server>



This directive appeared in version 0.7.0.





Specifies a I<C<file>> with trusted CA certificates in the PEM format
used to
L<verify|reference>
the HTTPS certificate
with L<Fetch API|reference>.







=head2 js_fetch_verify


B<syntax:> js_fetch_verify I<C<on> E<verbar> C<off>>


B<default:> I<on>


B<context:> I<stream>


B<context:> I<server>



This directive appeared in version 0.7.4.





Enables or disables verification of the HTTPS server certificate
with L<Fetch API|reference>.







=head2 js_fetch_verify_depth


B<syntax:> js_fetch_verify_depth I<I<C<number>>>


B<default:> I<100>


B<context:> I<stream>


B<context:> I<server>



This directive appeared in version 0.7.0.





Sets the verification depth in the HTTPS server certificates chain
with L<Fetch API|reference>.







=head2 js_filter


B<syntax:> js_filter I<I<C<function>> E<verbar> I<C<module.function>>>



B<context:> I<stream>


B<context:> I<server>





Sets a data filter.
Since L<0.4.0|changes>,
a module function can be referenced.
The filter function is called once at the moment when the stream session reaches
the L<content|stream_processing> phase.





The filter function is called with the following arguments:

=over


=item C<s>




the L<Stream Session|reference> object




=back







At this phase, it is possible to perform initialization
or register a callback with
the L<C<s.on()>|reference>
method for each incoming data chunk.
The
L<C<s.off()>|reference>
method may be used to unregister a callback and stop filtering.






B<NOTE>

As the C<js_filter> handler
returns its result immediately, it supports
only synchronous operations.
Thus, asynchronous operations such as
L<C<ngx.fetch()>|reference>
or
L<C<setTimeout()>|reference>
are not supported.








=head2 js_import


B<syntax:> js_import I<I<C<module.js>> E<verbar>
I<C<export_name from module.js>>>



B<context:> I<stream>


B<context:> I<server>



This directive appeared in version 0.4.0.





Imports a module that implements location and variable handlers in njs.
The C<export_name> is used as a namespace
to access module functions.
If the C<export_name> is not specified,
the module name will be used as a namespace.

    
    js_import stream.js;


Here, the module name C<stream> is used as a namespace
while accessing exports.
If the imported module exports C<foo()>,
C<stream.foo> is used to refer to it.





Several C<js_import> directives can be specified.






B<NOTE>

The directive can be specified on the
C<server> level
since L<0.7.7|changes>.








=head2 js_include


B<syntax:> js_include I<I<C<file>>>



B<context:> I<stream>





Specifies a file that implements server and variable handlers in njs:

    
    nginx.conf:
    js_include stream.js;
    js_set     $js_addr address;
    server {
        listen 127.0.0.1:12345;
        return $js_addr;
    }
    
    stream.js:
    function address(s) {
        return s.remoteAddress;
    }







The directive was made obsolete in version
L<0.4.0|changes>
and was removed in version
L<0.7.1|changes>.
The L</js_import> directive should be used instead.







=head2 js_path


B<syntax:> js_path I<
I<C<path>>>



B<context:> I<stream>


B<context:> I<server>



This directive appeared in version 0.3.0.





Sets an additional path for njs modules.






B<NOTE>

The directive can be specified on the
C<server> level
since L<0.7.7|changes>.








=head2 js_periodic


B<syntax:> js_periodic I<I<C<function>> E<verbar>
        I<C<module.function>>
        [C<interval>=I<C<time>>]
        [C<jitter>=I<C<number>>]
        [C<worker_affinity>=I<C<mask>>]>



B<context:> I<server>



This directive appeared in version 0.8.1.





Specifies a content handler to run at regular interval.
The handler receives a
L<session object|reference>
as its first argument,
it also has access to global objects such as
L<ngx|reference>.





The optional C<interval> parameter
sets the interval between two consecutive runs,
by default, 5 seconds.





The optional C<jitter> parameter sets the time within which
the location content handler will be randomly delayed,
by default, there is no delay.





By default, the C<js_handler> is executed on worker process 0.
The optional C<worker_affinity> 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<all> 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<syntax:> js_preload_object I<I<C<name.json>> E<verbar>
I<C<name>> from I<C<file.json>>>



B<context:> I<stream>


B<context:> I<server>



This directive appeared in version 0.7.8.





Preloads an
L<immutable object|preload_objects>
at configure time.
The C<name> is used as a name of the global variable
though which the object is available in njs code.
If the C<name> is not specified,
the file name will be used instead.

    
    js_preload_object map.json;


Here, the C<map> is used as a name
while accessing the preloaded object.





Several C<js_preload_object> directives can be specified.







=head2 js_preread


B<syntax:> js_preread I<I<C<function>> E<verbar> I<C<module.function>>>



B<context:> I<stream>


B<context:> I<server>





Sets an njs function which will be called at the
L<preread|stream_processing> phase.
Since L<0.4.0|changes>,
a module function can be referenced.





The function is called once
at the moment when the stream session reaches the
L<preread|stream_processing> phase
for the first time.
The function is called with the following arguments:


=over


=item C<s>




the L<Stream Session|reference> object




=back







At this phase, it is possible to perform initialization
or register a callback with
the L<C<s.on()>|reference>
method
for each incoming data chunk until one of the following methods are called:
L<C<s.allow()>|reference>,
L<C<s.decline()>|reference>,
L<C<s.done()>|reference>.
When one of these methods is called,
the stream session switches to the
L<next phase|stream_processing>
and all current
L<C<s.on()>|reference>
callbacks are dropped.






B<NOTE>

As the C<js_preread> handler
returns its result immediately, it supports
only synchronous callbacks.
Thus, asynchronous callbacks such as
L<C<ngx.fetch()>|reference>
or
L<C<setTimeout()>|reference>
are not supported.
Nevertheless, asynchronous operations are supported in
L<C<s.on()>|reference>
callbacks in the
L<preread|stream_processing> phase.
See
L<this example|https://github.com/nginx/njs-examples#authorizing-connections-using-ngx-fetch-as-auth-request-stream-auth-request> for more information.








=head2 js_set


B<syntax:> js_set I<
    I<C<$variable>>
    I<C<function>> E<verbar> I<C<module.function>>
    [C<nocache>]>



B<context:> I<stream>


B<context:> I<server>





Sets an njs C<function>
for the specified C<variable>.
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<phase|stream_processing>
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<ngx_stream_log_module> 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>, when
optional argument C<nocache> is provided the handler
is called every time it is referenced.
Due to current limitations
of the L<rewrite|ngx_stream_rewrite_module> module,
when a C<nocache> variable is referenced by the
L<set|ngx_stream_set_module> directive
its handler should always return a fixed-length value.






B<NOTE>

As the C<js_set> handler
returns its result immediately, it supports
only synchronous callbacks.
Thus, asynchronous callbacks such as
L<ngx.fetch()|reference>
or
L<setTimeout()|reference>
are not supported.







B<NOTE>

The directive can be specified on the
C<server> level
since L<0.7.7|changes>.








=head2 js_shared_dict_zone


B<syntax:> js_shared_dict_zone I<
    C<zone>=I<C<name>>:I<C<size>>
    [C<timeout>=I<C<time>>]
    [C<type>=C<string>E<verbar>C<number>]
    [C<evict>]>



B<context:> I<stream>



This directive appeared in version 0.8.0.





Sets the I<C<name>> and I<C<size>> of the shared memory zone
that keeps the
key-value L<dictionary|reference>
shared between worker processes.





By default the shared dictionary uses a string as a key and a value.
The optional C<type> parameter
allows redefining the value type to number.





The optional C<timeout> 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<timeout> argument of the
L<add|reference>,
L<incr|reference>, and
L<set|reference>
methods
(L<0.8.5|changes>).





The optional C<evict> 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<syntax:> js_var I<I<C<$variable>> [I<C<value>>]>



B<context:> I<stream>


B<context:> I<server>



This directive appeared in version 0.5.3.





Declares
a L<writable|reference>
variable.
The value can contain text, variables, and their combination.






B<NOTE>

The directive can be specified on the
C<server> level
since L<0.7.7|changes>.








=head1 Session Object Properties



Each stream njs handler receives one argument, a stream session
L<object|reference>.




