Extend NGINX With The New JavaScript Module
Written by Nikos Vaggalis   
Monday, 28 October 2024

Inject middleware functionality into NGINX with the expressive power of Javascript. NGINX JavaScript or NJS for short is a dynamic module under which you can use scripting for hooking into the NGINX execution model.

This means that with the NJS module you can:

  • Add complex access control and security checks before requests reach upstream servers

  • Manipulate response headers

  • Write flexible, asynchronous content handlers, filters, etc

For instance you could write a hello.js file that intercepts the request coming in to return a message to the client:

function hello(r) {
   r. return(200, "Hello world!\n");
}

export default {hello}

To import the JavaScript file and execute the function under specific circumstances, you modify the NGINX configuration as:


Of course, you'll be asking how this JavaScript code is executed.
The answer is that NGINX comes with an embedded Javascript engine customized to apply to NGINX's unique requirements. That aside, the JavaScript that NJS uses is a subset compliant with ES5 (ECMAScript 5. 1 Strict Variant) with some ES6 (ECMAScript 6) and newer extensions.

That means that you should not expect Node.js alike functionality, server side code execution or library capabilities like. Also NJS is not here to replace Lua scriopting which is the most popular way to write middleware code for NGINX but as an alternative aimed at those not familiar with Lua.

To install it you can build it from source or easier to use the package form: 

 package nginx-module-njs

After the package installation, the njs dynamic modules need to be loaded with the load_module directive:

load_module modules/ngx_http_js_module.so;

Then use it as the code displayed in the beginning of the article. You can also follow NGINX JavaScript examples to get started.

To conclude, njs brings another and more developer-friendly way to an existing and ever expanding arsenal of ways to extend NGINX's functionality.

 

More Information

njs

 

Related Articles

JSNation 2024 Sessions Now Available Online

 

 

 

To be informed about new articles on I Programmer, sign up for our weekly newsletter, subscribe to the RSS feed and follow us on Twitter, Facebook or Linkedin.

Banner


Looking Forward To NAO 7
03/11/2024

Introduced to the world in 2004 by its creator Bruno Maisonnier the kid-sized, autonomous humanoid robot NAO, turns 20 this year. At less than 2 ft tall, it is small in stature, but plays a big r [ ... ]



Azul Outperforms OpenJDK By Up To 37%
23/10/2024

Azul has announced that its Azul Platform Prime outperforms comparable OpenJDK distributions by as much as 37%. The company has also launched the Azul Java Performance Engineering Lab (JPEL) aimed at  [ ... ]


More News

espbook

 

Comments




or email your comment to: comments@i-programmer.info

Last Updated ( Monday, 28 October 2024 )