js_context_reuse

The `js_context_reuse` directive in NGINX allows for the reuse of JavaScript execution contexts across requests, enhancing performance and reducing memory overhead.

Syntaxjs_context_reuse on | off;
Defaultoff
Contextstream, stream server
Arguments1

Description

The js_context_reuse directive helps optimize the performance of NGINX when using its JavaScript module (NJS) by allowing the reuse of JavaScript execution contexts for multiple requests. Instead of creating a new context for each request, NGINX can maintain a pool of contexts. This reduces the overhead of context creation, minimizes garbage collection cycles, and can lead to improved response times, especially in high-load scenarios where many requests are processed in rapid succession.

This directive takes a single argument, which can be either 'on' or 'off'. When set to 'on', NGINX will attempt to reuse existing contexts for processing incoming requests. If set to 'off', a new context will be created for each request, which may be necessary in scenarios where different contexts must be isolated from each other for security or state management reasons. It's important to consider the implications of sharing a context, such as potential state bleed between requests if proper care is not taken.

In the context of streams and servers, this directive can significantly enhance the performance of event-driven applications, such as those relying on WebSocket communications or other long-lived connections, by reducing latency and improving the throughput of processed requests. The ability to share JavaScript execution contexts means that developers can focus on building features without overly worrying about resource allocation efficiency when handling multiple concurrent connections.

Config Example

stream {
    js_context_reuse on;
    server {
        listen 3000;
        js_content my_js_module;
    }
}

Ensure that your JavaScript code does not rely on request-specific state that could be shared across requests when using context reuse.

Monitor performance to ensure that reusing contexts does not introduce unexpected behavior due to shared state.

← Back to all directives