node.jsnginxnjs

Extend nginx via nodejs, njs script language


I found a section on the nginx docs that you can use

ECMAScript 5.1 (strict mode) with some ECMAScript 6 and later extensions

to extend nginx. As use case

Complex access control and security checks in njs before a request reaches an upstream server

https://nginx.org/en/docs/njs/

No i wonder if im able to connect to a database and do something similar as in node.js. Or even "run" node inside of the nginx process. But I think I have bad cards because there are currently only two modules, which provide no functionality like network sockets, but, there is a section "Using node modules with njs": https://nginx.org/en/docs/njs/node_modules.html.

Works this only with externeal libs or also with "node internals" like net, dgram, etc.?


Solution

  • is a subset of Javascript and currently lacks any means of interfacing with external processes directly, however can make sub-requests to local routes which can in turn proxy other services. I stumbled upon your question while researching a similar requirement and published a simple example here:

    The nearest thing to a solution effectively means creating a thin wrapper around your database connectivity and deploying it as an independent web-service, then setting up an internal route to reverse-proxy the connection:

    location /internal-service {
        internal;
        proxy_pass http://<hostname>:<port>;
    }
    

    Your njs script can then defer to the route by calling:

    response.subrequest(
        '/internal-service', 
        {
            method: 'GET',
        },
        serviceResponse => {
            // some logic... 
            response.return(200)
        }
    )
    

    There may be other workarounds but this approach seems to be the most robust at the moment. It does unfortunately make it difficult to develop self-contained modules - which I suspect is one of the reasons why there aren't really any reusable packages available.