js_import

The `js_import` directive integrates JavaScript modules into NGINX configuration by allowing the import of NJS scripts.

Syntaxjs_import string; | js_import string string string;
Defaultnone
Contextstream, stream server
Arguments1 or 3

Description

The js_import directive is a powerful feature in NGINX's JavaScript (NJS) module that allows users to import JavaScript files and modules directly into their NGINX configurations. This directive facilitates the reuse of JavaScript functions, enabling modular design for handling various web server tasks like request processing, filtering, and response handling. It supports one or three arguments, allowing for flexible configuration depending on the use case.

When specifying the directive, users can either import a single JavaScript file using a single argument, or provide the JavaScript filename along with an optional module alias and a function to be called upon import with three arguments. This capability is particularly useful for organizing larger applications into manageable units while adhering to principles of code reuse. The behavior of the js_import directive ensures that imported functions can be referenced within the configuration, making scripts dynamic and powerful.

The way in which js_import works is closely tied to the existing functionalities of NJS, which is designed to extend NGINX's capabilities using JavaScript syntax. As such, the imported scripts can utilize the full range of NJS features, including support for ECMAScript 5.1 and newer constructs, providing rich and modern capabilities for scripting NGINX operations.

Config Example

js_import my_script.js;

# or with parameters:
js_import my_script.js my_module myFunction;

Ensure the JavaScript file path is correct relative to the NGINX configuration directory.

If using multiple imports, be mindful of naming conflicts between functions or variables.

Check for errors in JavaScript syntax, as they can cause failures in NGINX reloads.

← Back to all directives