How to pass variable value from js file to nginx config with njs module

2.8k views Asked by At

I am trying to use njs to have chain request with nginx njs, i have below issue here is my javascript file and my scenario is I have two of API. I want to request first api and get it's reponse then append first api's response (cloud be JSON properties ) second api's header

async function chain(r) {
  r.headersOut["Content-Type"] = "application/json";
  var result = await r.subrequest("/validation", { method: "POST" });
  var json = JSON.parse(result.responseText);

  headers = json.fullName;// where to put this header and append it to second request header ?
  var result1 = await r.subrequest("/persistance");

  r.return(result1.status, result1.responseBody);

}

function getHeaders() {
  return headers;
}

export default { chain, getHeaders };

And my nginx config file

js_import http.js;
js_set $headers http.getHeaders; // here am trying to get headers from variable in http.js but is it alwat null and undefended
server {
    listen       80;
    listen  [::]:80;
    server_name  localhost;
       
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
       
    location ~ ^/.*$ {
      js_content http.chain;
    }

    location = /persistance {
       proxy_set_header accountId $headers; //it is always undefined, I think it is because declared on the top of file and it is nginx directives
       proxy_pass http://192.168.2.76:5001/academicyear/list;      
    }
     
    location = /validation {
       proxy_pass http://192.168.2.76:8088/v1/user/validation;
    }

}

I use subrequest and then it was the same issue

1

There are 1 answers

0
Manh Vu On

This comment might be the answer.

enter image description here

nginx does not support asynchronous operations (it is not related to the async keyword in JavaScript) in its variable handlers. When nginx wants the value of some variable (say $x_js_log) it finds it and calls its handler (js_log). Nginx cannot block here, and wants the result right away. r.subrequest() is an asynchronous operation by its nature.

https://github.com/nginx/njs/issues/287#issuecomment-584247289