js_preread

The `js_preread` directive allows the execution of JavaScript code before the stream is processed.

Syntaxjs_preread script;
Defaultnone
Contextstream, stream server
Arguments1

Description

The js_preread directive is part of the NGINX JavaScript module, enabling a flexible way to execute JavaScript before the processing of a stream. It can be particularly useful for handling tasks like protocol negotiation (e.g., determining whether to treat an incoming connection as HTTP, WebSocket, etc.) or for gathering specific connection data that may inform further processing decisions. This directive can accept a single JavaScript expression, which is executed during the initial stages when the server first accepts a connection.

When a connection arrives, NGINX will invoke the JavaScript specified in js_preread. The JavaScript function can perform various operations, such as inspecting connection metadata or determining the forwarding logic based on dynamic factors. The execution environment provides access to connection properties and can adapt behavior before any actual data transfer begins. This makes it a powerful tool for dynamic configurations based on incoming traffic characteristics.

Additionally, a common use case is to define specific handlers that interact with the stream, allowing developers to seamlessly integrate their JavaScript solutions directly into the NGINX stream processing workflow. This capability enhances NGINX's extensibility while retaining high performance for protocols handled in the stream context.

Config Example

stream {
    server {
        listen 12345;
        js_preread my_handler.js;
    }
}

Ensure the JavaScript code is compliant with NJS syntax; errors in the code may prevent the stream from functioning correctly.

Remember that js_preread can only be used in the stream and stream server contexts, not in HTTP contexts.

← Back to all directives