skip to Main Content

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.

2

Answers


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

    Login or Signup to reply.
  2. 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
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search