2

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.?

Emissary
  • 9,954
  • 8
  • 54
  • 65
Marc
  • 2,920
  • 3
  • 14
  • 30

1 Answers1

2

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.

Emissary
  • 9,954
  • 8
  • 54
  • 65
  • Works the subrequest only on a location block defined in the nginx config file or also on a full external url e.g ```http://127.0.0.1:4500```? – Marc Apr 02 '21 at 10:24
  • 1
    I did test that too, `subrequest` cannot call a fully-qualified address, it can only see local routes - so an intermediary proxy route has to be defined in your nginx config (co-located in the same `server` block), regardless of whether the proxied services is running locally, on a different port or remotely. – Emissary Apr 02 '21 at 11:56
  • 1
    @Emissary have you given a try to the Fetch API https://nginx.org/en/docs/njs/reference.html#ngx_fetch no need for subrequest – bhantol Jun 22 '23 at 15:25
  • 1
    @bhantol It does indeed look like a better alternative. My write-up here is a few years old and only documents the support that was commonly available at the time. – Emissary Jun 22 '23 at 23:59