W3cubDocs

/nginx

njs scripting language

njs is a subset of the JavaScript language that allows extending nginx functionality. njs is created in compliance with ECMAScript 5.1 (strict mode) with some ECMAScript 6 and later extensions. The compliance is still evolving.

Use cases

  • Complex access control and security checks in njs before a request reaches an upstream server
  • Manipulating response headers
  • Writing flexible asynchronous content handlers and filters

See examples and blog posts for more njs use cases.

Basic HTTP Example

To use njs in nginx:

  • install njs scripting language

  • create an njs script file, for example, hello_world.js. See Reference for the list of njs properties and methods.

    function hello(r) {
        r.return(200, "Hello world!");
    }
    
  • in the nginx.conf file, enable ngx_http_js_module module and specify the js_include directive with the hello_world.js script file:

    load_module modules/ngx_http_js_module.so;
    
    events {}
    
    http {
        js_include hello_world.js;
    
        server {
            listen 8000;
    
            location / {
                js_content hello;
            }
        }
    }
    
    

There is also a standalone command line utility that can be used independently of nginx for njs development and debugging.

Presentation at nginx.conf 2018

© 2002-2018 Igor Sysoev
© 2011-2018 Nginx, Inc.
Licensed under the BSD License.
https://nginx.org/en/docs/njs/index.html