1

Is it possible to persist some data in the javascript module of nginx?

I need to safe some data from the request to validate if the following requests are allowed.

Oliver Stahl
  • 617
  • 3
  • 19

2 Answers2

1

I would recommend to use ngx_http_keyval_module. it allows to keep key-value dictionaries in the shared memory available to all requests and workers.

Take a look at the number of requests per client IP example.

nginx.conf

...

http {
  js_path "/etc/nginx/njs/";

  js_import num_requests_module from logging/num_requests_module.js;
  js_set $num_requests num_requests_module.num_requests;

  keyval_zone zone=foo:10m;    
  keyval $remote_addr $foo zone=foo;

  log_format bar '$remote_addr [$time_local] $num_requests';

  access_log logs/access.log bar;

  server {
        listen 80;

        location / {
            return 200;
        }
  }
}

num_requests_module.js:

function num_requests(r) {
    var n = r.variables.foo; // read variable from the share memory
    n = n ? Number(n) + 1 : 1;
    r.variables.foo = n; // persist variable in the shared memory
    return n;
}

export default {num_requests};

Checking:

curl http://localhost/aa; curl http://localhost/aa; curl http://localhost/aa
curl --interface 127.0.0.2 http://localhost/aa; curl --interface 127.0.0.2 http://localhost/aa

docker logs njs_example
127.0.0.1 [22/Nov/2021:16:55:06 +0000] 1
127.0.0.1 [22/Nov/2021:16:55:07 +0000] 2
127.0.0.1 [22/Nov/2021:16:55:29 +0000] 3
127.0.0.2 [22/Nov/2021:18:20:24 +0000] 1
127.0.0.2 [22/Nov/2021:18:20:25 +0000] 2
ursa
  • 4,404
  • 1
  • 24
  • 38
0

I would try to use it by writing a file and reading it. https://github.com/nginx/njs/issues/75 Here is someone kinda using it. Second idea would be to just try to setup it as a nginx variable or something. https://www.docs4dev.com/docs/en/nginx/current/reference/http-ngx_http_js_module.html

Maxrain
  • 221
  • 1
  • 4
  • 10
  • Files are to slow, and i cant use nginx variables in javascript :/ – Oliver Stahl Sep 14 '21 at 12:37
  • per-request parsing on the shared source (file) is far from the data sharing... NJS variables are per-request entities, thus they could NOT be shared between requests – ursa Nov 27 '22 at 12:47