Is there a way to access nginx.var in javascript

1.2k views Asked by At

I have some nginx variables defied in my server_content.conf file is there a way we can access it in my .js file? servercontent.conf ... set $debug_log 'off'; ...

logging.js if(ngx.var.debug_log = 'on') .. do something

1

There are 1 answers

11
Ivan Shatsky On

Using the SSI

The first way of how this can be solved is to use the Server Side Includes module.

Here is a brief example:

  • nginx configuration fragment:
set $debug_log on;
location / {
    ssi on;
    ssi_types application/javascript;
    ...
}
  • logging.js example
var logging = '<!--# echo var="debug_log" -->';
console.log("Debug status detected via SSI substitution is", logging);

Read the module documentation to find out all the available features.

For the security purposes, if there is the only JS file you want to be able to receive some data from nginx, declare an individual location for this file (this will also speed-up all the other JS content being served), for example if its URI is /js/logging.js:

location / {
    ... # default location
}
location = /js/logging.js {
    # do not cache this file at the client side
    add_header Cache-Control "no-cache, no-store, must-revalidate";
    ssi on;
    ssi_types application/javascript;
}

Using the AJAX endpoint

The second way to solve this is to define an AJAX endpoint with the nginx configuration:

location = /getdebug {
    default_type application/json;
    return 200 '{"logging":"$debug_log"}';
}

Now the $debug_log nginx value can be acquired using the AJAX call from the browser-side JavaScript code:

const xhr = new XMLHttpRequest();
xhr.open('GET', '/getdebug');
xhr.responseType = 'json';
xhr.onload = function() {
    if (this.status == 200) {
        console.log('Debug status detected via AJAX request is', this.response.logging);
    }
};

Update 1

Turns out the whole question was about njs rather than browser-side JavaScript. In theory this can be achieved via the subrequests API using responseBuffer or even responseText subrequest object properties. You can look at the Setting nginx var as a result of async operation examples, especially this one, using some kind of more simple plain text endpoint:

location = /getdebug {
    default_type text/plain;
    return 200 $debug_log;
}

Unfortunately I'm not familiar with the njs (I use the lua-nginx-module for the similar purposes) and don't know if there is a more straight way to do it (which is probably exists).

Additionally, if you are trying to use Node modules with njs, make sure you read the Using node modules with njs documentation chapter.


Update 2

All nginx variables (which are evaluated on per-request basis) are available in the njs code via r.variables{} HTTP Request object property, e.g.

if (r.variables.debug_log == 'on') {
    ... do something
}