### Install uWebSockets.js Source: https://github.com/unetworking/uwebsockets.js/blob/master/README.md Install uWebSockets.js using the NPM client. Specify the version for installation. ```bash npm install uNetworking/uWebSockets.js#v20.67.0 ``` -------------------------------- ### Install uWebSockets.js using Version Tag Source: https://github.com/unetworking/uwebsockets.js/blob/master/misc/npm.md Install uWebSockets.js from its GitHub repository using a specific version tag. Replace 'v20.43.0' with the desired release version. ```bash npm install uNetworking/uWebSockets.js#v20.43.0 ``` -------------------------------- ### Install uWebSockets.js using SHA-1 Hash Source: https://github.com/unetworking/uwebsockets.js/blob/master/misc/npm.md Install uWebSockets.js from its GitHub repository using a specific SHA-1 hash for guaranteed integrity. Replace '1977b5039938ad863d42fc4958d48c17e5a1fa06' with the desired commit hash. ```bash npm install uNetworking/uWebSockets.js#1977b5039938ad863d42fc4958d48c17e5a1fa06 ``` -------------------------------- ### GET /pattern Source: https://github.com/unetworking/uwebsockets.js/blob/master/docs/generated/interfaces/TemplatedApp.html Registers an HTTP GET handler for a specific URL pattern. ```APIDOC ## GET [pattern] ### Description Registers an HTTP GET handler matching specified URL pattern. ### Method GET ### Parameters #### Path Parameters - **pattern** (RecognizedString) - Required - The URL pattern to match. - **handler** ((res: HttpResponse, req: HttpRequest) => void | Promise) - Required - The handler function for the request. ``` -------------------------------- ### Get Subscribed Topics Source: https://github.com/unetworking/uwebsockets.js/blob/master/docs/generated/interfaces/WebSocket.html Returns an array of topics that the WebSocket connection is currently subscribed to. ```typescript getTopics(): string[]; ``` -------------------------------- ### WebSocket Max Backpressure Setting Source: https://github.com/unetworking/uwebsockets.js/blob/master/docs/generated/interfaces/WebSocketBehavior.html Defines the maximum allowed backpressure in bytes before messages start being dropped. ```typescript maxBackpressure?: number; ``` -------------------------------- ### Get Buffered Amount Source: https://github.com/unetworking/uwebsockets.js/blob/master/docs/generated/interfaces/WebSocket.html Returns the number of bytes currently buffered in the backpressure queue for this WebSocket connection. This is analogous to the browser's bufferedAmount property. ```typescript getBufferedAmount(): number; ``` -------------------------------- ### App Constructor Source: https://github.com/unetworking/uwebsockets.js/blob/master/docs/generated/functions/App.html Initializes a new non-SSL uWebSockets.js application instance. ```APIDOC ## App(options) ### Description Constructs a non-SSL app. An app is your starting point where you attach behavior to URL routes. This is also where you listen and run your app. ### Parameters #### Path Parameters - **options** (AppOptions) - Optional - Configuration options for the application. ### Returns - **TemplatedApp** - The initialized application instance. ``` -------------------------------- ### listen() - Host, Port, and Options Source: https://github.com/unetworking/uwebsockets.js/blob/master/docs/generated/interfaces/TemplatedApp.html Listens to a specified hostname and port with additional options. The callback function receives either false or a listen socket. ```APIDOC ## POST /listen ### Description Listens to hostname & port and sets Listen Options. Callback hands either false or a listen socket. ### Method POST ### Endpoint /listen ### Parameters #### Path Parameters - None #### Query Parameters - **host** (RecognizedString) - Required - The hostname to listen on. - **port** (number) - Required - The port number to listen on. - **options** (ListenOptions) - Required - Options for listening. #### Request Body - **cb** ((listenSocket: false | us_listen_socket) => void | Promise) - Required - Callback function to handle the listen socket. ### Request Example ```json { "host": "localhost", "port": 3000, "options": {"compression": 1}, "cb": "(listenSocket) => { console.log('Listening with options'); }" } ``` ### Response #### Success Response (200) - **TemplatedApp[]** - An array of TemplatedApp objects. #### Response Example ```json [ {} ] ``` ``` -------------------------------- ### Get User Data Source: https://github.com/unetworking/uwebsockets.js/blob/master/docs/generated/interfaces/WebSocket.html Retrieves the user-defined data associated with this WebSocket connection. ```typescript getUserData(): UserData; ``` -------------------------------- ### AppOptions Interface Source: https://github.com/unetworking/uwebsockets.js/blob/master/docs/generated/interfaces/AppOptions.html Configuration options for SSLApp construction in uWebSockets.js. ```APIDOC ## AppOptions Interface ### Description Options used when constructing an app, specifically for SSLApp. These options are passed directly to the underlying uSockets C layer. ### Request Body - **ca_file_name** (RecognizedString) - Optional - Path to the CA certificate file. - **cert_file_name** (RecognizedString) - Optional - Path to the certificate file. - **dh_params_file_name** (RecognizedString) - Optional - Path to the Diffie-Hellman parameters file. - **key_file_name** (RecognizedString) - Optional - Path to the private key file. - **passphrase** (RecognizedString) - Optional - Passphrase for the SSL certificate. - **ssl_ciphers** (RecognizedString) - Optional - SSL ciphers to be used. - **ssl_prefer_low_memory_usage** (boolean) - Optional - If true, translates to SSL_MODE_RELEASE_BUFFERS to optimize memory usage. ``` -------------------------------- ### Get Remote Port Source: https://github.com/unetworking/uwebsockets.js/blob/master/docs/generated/interfaces/WebSocket.html Retrieves the remote port number of the WebSocket connection. ```typescript getRemotePort(): number; ``` -------------------------------- ### listen() - Port and Options Source: https://github.com/unetworking/uwebsockets.js/blob/master/docs/generated/interfaces/TemplatedApp.html Listens to a specified port with additional options. The callback function receives either false or a listen socket. ```APIDOC ## POST /listen ### Description Listens to port and sets Listen Options. Callback hands either false or a listen socket. ### Method POST ### Endpoint /listen ### Parameters #### Path Parameters - None #### Query Parameters - **port** (number) - Required - The port number to listen on. - **options** (ListenOptions) - Required - Options for listening. #### Request Body - **cb** ((listenSocket: false | us_listen_socket) => void | Promise) - Required - Callback function to handle the listen socket. ### Request Example ```json { "port": 3000, "options": {"compression": 1}, "cb": "(listenSocket) => { console.log('Listening with options'); }" } ``` ### Response #### Success Response (200) - **TemplatedApp[]** - An array of TemplatedApp objects. #### Response Example ```json [ {} ] ``` ``` -------------------------------- ### App and SSLApp Initialization Source: https://github.com/unetworking/uwebsockets.js/blob/master/docs/generated/index.html Functions to initialize a standard or SSL-enabled uWebSockets application. ```APIDOC ## App ### Description Initializes a standard uWebSockets application. ### Method Function ## SSLApp ### Description Initializes a uWebSockets application with SSL support. ### Method Function ``` -------------------------------- ### Get Remote Address Source: https://github.com/unetworking/uwebsockets.js/blob/master/docs/generated/interfaces/WebSocket.html Retrieves the remote IP address of the WebSocket connection as an ArrayBuffer. ```typescript getRemoteAddress(): ArrayBuffer; ``` -------------------------------- ### SSLApp Constructor Source: https://github.com/unetworking/uwebsockets.js/blob/master/docs/generated/functions/SSLApp.html Constructs an SSL-enabled application instance using the specified configuration options. ```APIDOC ## SSLApp ### Description Constructs an SSL app. See App for general application functionality. ### Parameters #### Path Parameters - **options** (AppOptions) - Required - Configuration options for the SSL application. ### Returns - **TemplatedApp** - An instance of a TemplatedApp configured with SSL. ``` -------------------------------- ### Get Remote Address as Text Source: https://github.com/unetworking/uwebsockets.js/blob/master/docs/generated/interfaces/WebSocket.html Retrieves the remote IP address of the WebSocket connection as a text-based ArrayBuffer. ```typescript getRemoteAddressAsText(): ArrayBuffer; ``` -------------------------------- ### listen() - Host and Port Source: https://github.com/unetworking/uwebsockets.js/blob/master/docs/generated/interfaces/TemplatedApp.html Listens to a specified hostname and port. The callback function receives either false or a listen socket. ```APIDOC ## POST /listen ### Description Listens to hostname & port. Callback hands either false or a listen socket. ### Method POST ### Endpoint /listen ### Parameters #### Path Parameters - None #### Query Parameters - **host** (RecognizedString) - Required - The hostname to listen on. - **port** (number) - Required - The port number to listen on. #### Request Body - **cb** ((listenSocket: false | us_listen_socket) => void | Promise) - Required - Callback function to handle the listen socket. ### Request Example ```json { "host": "localhost", "port": 3000, "cb": "(listenSocket) => { console.log('Listening on port 3000'); }" } ``` ### Response #### Success Response (200) - **TemplatedApp[]** - An array of TemplatedApp objects. #### Response Example ```json [ {} ] ``` ``` -------------------------------- ### any Source: https://github.com/unetworking/uwebsockets.js/blob/master/docs/generated/interfaces/TemplatedApp.html Registers an HTTP handler for any HTTP method matching a specified URL pattern. ```APIDOC ## any ### Description Registers an HTTP handler that matches the specified URL pattern for any HTTP method. ### Method ANY ### Endpoint /api/any/{pattern} ### Parameters #### Path Parameters - **pattern** (RecognizedString) - Required - The URL pattern to match. #### Query Parameters N/A #### Request Body - **handler** (function) - Required - The handler function to execute. It receives HttpResponse and HttpRequest objects. ### Request Example ```javascript app.any('/some/path', (res, req) => { // handler logic }); ``` ### Response #### Success Response (200) - **status** (string) - Indicates the handler was registered. #### Response Example ```json { "status": "registered" } ``` ``` -------------------------------- ### DEDICATED_COMPRESSOR_64KB Configuration Source: https://github.com/unetworking/uwebsockets.js/blob/master/docs/generated/variables/DEDICATED_COMPRESSOR_64KB.html Configuration option for enabling a dedicated 64KB compress window per socket. ```APIDOC ## Variable DEDICATED_COMPRESSOR_64KB ### Description Enables a sliding dedicated compress window, requiring 64KB of memory per socket. ### Type CompressOptions ### Defined In index.d.ts:433 ### Settings * Protected * Inherited ``` -------------------------------- ### ListenOptions Enumeration Source: https://github.com/unetworking/uwebsockets.js/blob/master/docs/generated/enums/ListenOptions.html Defines the available options for server listening configurations in uWebSockets.js. ```APIDOC ## ListenOptions Enumeration ### Description Defines flags used to configure the behavior of the server when listening on a port. ### Enumeration Members - **LIBUS_LISTEN_DEFAULT** (number: 0) - The default listening behavior. - **LIBUS_LISTEN_EXCLUSIVE_PORT** (number: 1) - Indicates that the port should be opened in exclusive mode. ``` -------------------------------- ### addServerName Source: https://github.com/unetworking/uwebsockets.js/blob/master/docs/generated/interfaces/TemplatedApp.html Adds a server name to the application. ```APIDOC ## addServerName ### Description Adds a server name to the application, allowing it to respond to requests for a specific hostname. ### Method POST ### Endpoint /api/addServerName ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body - **hostname** (string) - Required - The hostname to add. - **options** (AppOptions) - Required - The options for the server name. ### Request Example ```json { "hostname": "example.com", "options": { ... } } ``` ### Response #### Success Response (200) - **message** (string) - Confirmation message. #### Response Example ```json { "message": "Server name added successfully." } ``` ``` -------------------------------- ### connect Source: https://github.com/unetworking/uwebsockets.js/blob/master/docs/generated/interfaces/TemplatedApp.html Registers an HTTP CONNECT handler for a specified URL pattern. ```APIDOC ## connect ### Description Registers an HTTP CONNECT handler that matches the specified URL pattern. ### Method CONNECT ### Endpoint /api/connect/{pattern} ### Parameters #### Path Parameters - **pattern** (RecognizedString) - Required - The URL pattern to match for CONNECT requests. #### Query Parameters N/A #### Request Body - **handler** (function) - Required - The handler function to execute for CONNECT requests. It receives HttpResponse and HttpRequest objects. ### Request Example ```javascript app.connect('/tunnel', (res, req) => { // CONNECT handler logic }); ``` ### Response #### Success Response (200) - **status** (string) - Indicates the handler was registered. #### Response Example ```json { "status": "registered" } ``` ``` -------------------------------- ### TemplatedApp Interface Methods Source: https://github.com/unetworking/uwebsockets.js/blob/master/docs/generated/interfaces/TemplatedApp.html This section details the various methods available on the TemplatedApp interface for managing HTTP routes, server options, and application lifecycle. ```APIDOC ## TemplatedApp Interface TemplatedApp is either an SSL or non-SSL app. See App for more info, read user manual. ### Methods - **addChildAppDescriptor**(descriptor: AppDescriptor): void Adds a child application descriptor. - **addServerName**(hostname: string, options: AppOptions): TemplatedApp Adds a server name with specified options. - **any**(pattern: RecognizedString, handler: (res: HttpResponse, req: HttpRequest) => void | Promise): TemplatedApp Handles any HTTP method for a given pattern. - **close**(): TemplatedApp Closes the application. - **connect**(pattern: RecognizedString, handler: (res: HttpResponse, req: HttpRequest) => void | Promise): TemplatedApp Handles WebSocket upgrade requests for a given pattern. - **del**(pattern: RecognizedString, handler: (res: HttpResponse, req: HttpRequest) => void | Promise): TemplatedApp Handles DELETE requests for a given pattern. - **domain**(domain: string): TemplatedApp Sets the domain for the application. - **filter**(cb: (res: HttpResponse, count: Number) => void | Promise): TemplatedApp Applies a filter to incoming requests. - **get**(pattern: RecognizedString, handler: (res: HttpResponse, req: HttpRequest) => void | Promise): TemplatedApp Handles GET requests for a given pattern. - **getDescriptor**(): AppDescriptor Retrieves the application descriptor. - **head**(pattern: RecognizedString, handler: (res: HttpResponse, req: HttpRequest) => void | Promise): TemplatedApp Handles HEAD requests for a given pattern. - **listen**(host: RecognizedString, port: number, cb: (listenSocket: false | us_listen_socket) => void | Promise): TemplatedApp Starts listening on a specific host and port with a callback. - **listen**(host: RecognizedString, port: number, options: ListenOptions, cb: (listenSocket: false | us_listen_socket) => void | Promise): TemplatedApp Starts listening on a specific host and port with options and a callback. - **listen**(port: number, cb: (listenSocket: false | us_listen_socket) => void | Promise): TemplatedApp Starts listening on a specific port with a callback. - **listen**(port: number, options: ListenOptions, cb: (listenSocket: false | us_listen_socket) => void | Promise): TemplatedApp Starts listening on a specific port with options and a callback. - **listen_unix**(cb: (listenSocket: us_listen_socket) => void | Promise, path: RecognizedString): TemplatedApp Starts listening on a Unix domain socket. - **missingServerName**(cb: (hostname: string) => void): TemplatedApp Callback for when a server name is missing. - **numSubscribers**(topic: RecognizedString): number Gets the number of subscribers for a given topic. - **options**(pattern: RecognizedString, handler: (res: HttpResponse, req: HttpRequest) => void | Promise): TemplatedApp Handles OPTIONS requests for a given pattern. - **patch**(pattern: RecognizedString, handler: (res: HttpResponse, req: HttpRequest) => void | Promise): TemplatedApp Handles PATCH requests for a given pattern. - **post**(pattern: RecognizedString, handler: (res: HttpResponse, req: HttpRequest) => void | Promise): TemplatedApp Handles POST requests for a given pattern. - **publish**(topic: RecognizedString, message: RecognizedString, isBinary?: boolean, compress?: boolean): boolean Publishes a message to a topic. - **put**(pattern: RecognizedString, handler: (res: HttpResponse, req: HttpRequest) => void | Promise): TemplatedApp Handles PUT requests for a given pattern. ``` -------------------------------- ### cork() Source: https://github.com/unetworking/uwebsockets.js/blob/master/docs/generated/interfaces/HttpResponse.html Optimizes network and CPU usage by grouping multiple write operations into a single atomic IO operation. ```APIDOC ## cork() ### Description Corking a response is a performance improvement in both CPU and network, as you ready the IO system for writing multiple chunks at once. This is essential when performing async operations where the default corking context is lost. ### Parameters - **cb** (function) - Required - A callback function containing write operations like writeStatus, writeHeader, or write. ### Response - **HttpResponse** - Returns the current response object. ``` -------------------------------- ### listen_unix() Source: https://github.com/unetworking/uwebsockets.js/blob/master/docs/generated/interfaces/TemplatedApp.html Listens to a Unix socket. The callback function receives a listen socket. ```APIDOC ## POST /listen_unix ### Description Listens to unix socket. Callback hands either false or a listen socket. ### Method POST ### Endpoint /listen_unix ### Parameters #### Path Parameters - None #### Query Parameters - **path** (RecognizedString) - Required - The path to the Unix socket. #### Request Body - **cb** ((listenSocket: us_listen_socket) => void | Promise) - Required - Callback function to handle the listen socket. ### Request Example ```json { "path": "/tmp/uws.sock", "cb": "(listenSocket) => { console.log('Listening on Unix socket'); }" } ``` ### Response #### Success Response (200) - **TemplatedApp[]** - An array of TemplatedApp objects. #### Response Example ```json [ {} ] ``` ``` -------------------------------- ### DEDICATED_COMPRESSOR_256KB Configuration Source: https://github.com/unetworking/uwebsockets.js/blob/master/docs/generated/variables/DEDICATED_COMPRESSOR_256KB.html The DEDICATED_COMPRESSOR_256KB option configures a dedicated compression window for each socket, requiring 256KB of memory per socket. ```APIDOC ## DEDICATED_COMPRESSOR_256KB ### Description Configures a dedicated compress window, requiring 256KB of memory per socket. ### Type CompressOptions ### Source Defined in [index.d.ts:437](https://github.com/uNetworking/uWebSockets.js/blob/master/docs/index.d.ts#L437) ### Settings * Protected * Inherited ``` -------------------------------- ### HEAD /pattern Source: https://github.com/unetworking/uwebsockets.js/blob/master/docs/generated/interfaces/TemplatedApp.html Registers an HTTP HEAD handler for a specific URL pattern. ```APIDOC ## HEAD [pattern] ### Description Registers an HTTP HEAD handler matching specified URL pattern. ### Method HEAD ### Parameters #### Path Parameters - **pattern** (RecognizedString) - Required - The URL pattern to match. - **handler** ((res: HttpResponse, req: HttpRequest) => void | Promise) - Required - The handler function for the request. ``` -------------------------------- ### forEach Source: https://github.com/unetworking/uwebsockets.js/blob/master/docs/generated/interfaces/HttpRequest.html Iterates over a collection, executing a callback for each item. ```APIDOC ## forEach ### Description Iterates over a collection, executing a callback for each item. ### Method Not applicable (this is a utility method). ### Endpoint Not applicable. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### listen() - Port Only Source: https://github.com/unetworking/uwebsockets.js/blob/master/docs/generated/interfaces/TemplatedApp.html Listens to a specified port. The callback function receives either false or a listen socket. ```APIDOC ## POST /listen ### Description Listens to port. Callback hands either false or a listen socket. ### Method POST ### Endpoint /listen ### Parameters #### Path Parameters - None #### Query Parameters - **port** (number) - Required - The port number to listen on. #### Request Body - **cb** ((listenSocket: false | us_listen_socket) => void | Promise) - Required - Callback function to handle the listen socket. ### Request Example ```json { "port": 3000, "cb": "(listenSocket) => { console.log('Listening on port 3000'); }" } ``` ### Response #### Success Response (200) - **TemplatedApp[]** - An array of TemplatedApp objects. #### Response Example ```json [ {} ] ``` ``` -------------------------------- ### upgrade Source: https://github.com/unetworking/uwebsockets.js/blob/master/docs/generated/interfaces/HttpResponse.html Upgrades an HttpResponse to a WebSocket connection. ```APIDOC ## upgrade ### Description Upgrades a HttpResponse to a WebSocket. See UpgradeAsync, UpgradeSync example files. ### Parameters - **userData** (UserData) - Required - User data associated with the socket. - **secWebSocketKey** (RecognizedString) - Required - The Sec-WebSocket-Key header value. - **secWebSocketProtocol** (RecognizedString) - Required - The Sec-WebSocket-Protocol header value. - **secWebSocketExtensions** (RecognizedString) - Required - The Sec-WebSocket-Extensions header value. - **context** (us_socket_context_t) - Required - The socket context. ### Response - **Returns** (void) ``` -------------------------------- ### tryEnd Source: https://github.com/unetworking/uwebsockets.js/blob/master/docs/generated/interfaces/HttpResponse.html Ends the response by streaming chunks, used with onWritable. ```APIDOC ## tryEnd ### Description Ends this response, or tries to, by streaming appropriately sized chunks of body. ### Parameters - **fullBodyOrChunk** (RecognizedString) - Required - The data to send. - **totalSize** (number) - Required - Total size of the body. ### Returns - **[boolean, boolean]** - Tuple containing [ok, hasResponded]. ``` -------------------------------- ### DEDICATED_DECOMPRESSOR_2KB Configuration Source: https://github.com/unetworking/uwebsockets.js/blob/master/docs/generated/variables/DEDICATED_DECOMPRESSOR_2KB.html Information about the DEDICATED_DECOMPRESSOR_2KB setting, which configures a dedicated decompress window for sockets. ```APIDOC ## Variable DEDICATED_DECOMPRESSOR_2KB ### Description Sliding dedicated decompress window, requires 2KB of memory per socket (plus about 23KB). ### Type [CompressOptions](../types/CompressOptions.html) ### Defined in [index.d.ts:447](https://github.com/uNetworking/uWebSockets.js/blob/master/docs/index.d.ts#L447) ### Settings - Member Visibility: Protected, Inherited ``` -------------------------------- ### DEDICATED_COMPRESSOR_4KB Configuration Source: https://github.com/unetworking/uwebsockets.js/blob/master/docs/generated/variables/DEDICATED_COMPRESSOR_4KB.html Details the DEDICATED_COMPRESSOR_4KB variable, which configures a dedicated compress window requiring 4KB of memory per socket. ```APIDOC ## Variable DEDICATED_COMPRESSOR_4KB ### Description Configures a sliding dedicated compress window that requires 4KB of memory per socket. ### Type [CompressOptions](../types/CompressOptions.html) ### Defined in * [index.d.ts:425](https://github.com/uNetworking/uWebSockets.js/blob/master/docs/index.d.ts#L425) ### Settings * Member Visibility: Protected, Inherited ``` -------------------------------- ### WebSocket Configuration Properties Source: https://github.com/unetworking/uwebsockets.js/blob/master/docs/generated/interfaces/WebSocketBehavior.html Overview of the available properties for configuring WebSocket behavior in uWebSockets.js. ```APIDOC ## WebSocket Properties ### Description These properties define the behavior, limits, and event handlers for WebSocket connections within uWebSockets.js. ### Properties - **close** - Event handler for connection closure. - **closeOnBackpressureLimit** - Boolean flag to close connection when backpressure limit is reached. - **compression** - Configuration for per-message deflate compression. - **drain** - Event handler for when backpressure is cleared. - **dropped** - Event handler for dropped messages. - **idleTimeout** - Maximum time in seconds a connection can be idle. - **maxBackpressure** - Maximum allowed backpressure in bytes. - **maxLifetime** - Maximum lifetime of a connection in seconds. - **maxPayloadLength** - Maximum allowed message payload length in bytes. - **message** - Event handler for incoming messages. - **open** - Event handler for successful connection opening. - **ping** - Event handler for incoming pings. - **pong** - Event handler for incoming pongs. - **sendPingsAutomatically** - Boolean flag to enable automatic ping frames. - **subscription** - Event handler for subscription events. - **upgrade** - Event handler for HTTP upgrade requests. ``` -------------------------------- ### ws Source: https://github.com/unetworking/uwebsockets.js/blob/master/docs/generated/interfaces/TemplatedApp.html Registers a WebSocket handler for a specified URL pattern. ```APIDOC ## ws ### Description Registers a WebSocket handler for connections matching the specified URL pattern. ### Method GET ### Endpoint /api/ws/{pattern} ### Parameters #### Path Parameters - **pattern** (RecognizedString) - Required - The URL pattern to match for WebSocket connections. #### Query Parameters N/A #### Request Body - **behavior** (WebSocketBehavior) - Required - The WebSocket behavior configuration. ### Request Example ```javascript app.ws('/chat', { open: ws => { console.log('connected'); }, message: (ws, message) => { console.log(message); }, close: ws => { console.log('disconnected'); } }); ``` ### Response #### Success Response (200) - **status** (string) - Indicates the handler was registered. #### Response Example ```json { "status": "registered" } ``` ``` -------------------------------- ### Socket Management Source: https://github.com/unetworking/uwebsockets.js/blob/master/docs/generated/index.html Functions for interacting with listen sockets and retrieving socket information. ```APIDOC ## us_listen_socket_close ### Description Closes a listen socket. ### Method Function ## us_socket_local_port ### Description Retrieves the local port of a socket. ### Method Function ``` -------------------------------- ### HTTP OPTIONS Handler Source: https://github.com/unetworking/uwebsockets.js/blob/master/docs/generated/interfaces/TemplatedApp.html Registers an HTTP OPTIONS handler for a specified URL pattern. ```APIDOC ## OPTIONS /:pattern ### Description Registers an HTTP OPTIONS handler matching the specified URL pattern. ### Method OPTIONS ### Endpoint /:pattern ### Parameters #### Path Parameters - **pattern** (RecognizedString) - Required - The URL pattern to match. #### Request Body - **handler** ((res: HttpResponse, req: HttpRequest) => void | Promise) - Required - The handler function to execute. ### Response #### Success Response (200) - **TemplatedApp** - Returns the TemplatedApp instance for chaining. #### Response Example (No specific example provided in the source text for the response body, but the return type is TemplatedApp.) ``` -------------------------------- ### getMethod Source: https://github.com/unetworking/uwebsockets.js/blob/master/docs/generated/interfaces/HttpRequest.html Retrieves the HTTP method. ```APIDOC ## getMethod ### Description Retrieves the HTTP method. ### Method Not applicable (this is a utility method). ### Endpoint Not applicable. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### WebSocket Configuration Options Source: https://github.com/unetworking/uwebsockets.js/blob/master/docs/generated/interfaces/WebSocketBehavior.html Configuration properties for defining WebSocket behavior such as timeouts, payload limits, and backpressure management. ```APIDOC ## WebSocket Configuration Options ### Description Settings to control the behavior and limits of WebSocket connections. ### Parameters - **idleTimeout** (number) - Optional - Maximum seconds without activity before closing. Defaults to 120. - **maxBackpressure** (number) - Optional - Maximum length of allowed backpressure per socket. Defaults to 64 * 1024. - **maxLifetime** (number) - Optional - Maximum minutes a WebSocket may be connected. 0 disables. - **maxPayloadLength** (number) - Optional - Maximum length of received message. Defaults to 16 * 1024. - **sendPingsAutomatically** (boolean) - Optional - Whether to automatically send pings to maintain connection. ``` -------------------------------- ### Connection Information Methods Source: https://github.com/unetworking/uwebsockets.js/blob/master/docs/generated/interfaces/HttpResponse.html Methods to retrieve remote address and port information, including support for PROXY Protocol v2. ```APIDOC ## Connection Information Methods ### Methods - **getRemoteAddress()**: Returns remote IP in binary format. - **getRemoteAddressAsText()**: Returns remote IP as text. - **getRemotePort()**: Returns remote port number. - **getProxiedRemoteAddress()**: Returns proxied remote IP in binary format. - **getProxiedRemoteAddressAsText()**: Returns proxied remote IP as text. - **getProxiedRemotePort()**: Returns proxied remote port number. ### Returns - **ArrayBuffer** or **number** depending on the method. ``` -------------------------------- ### getQuery Source: https://github.com/unetworking/uwebsockets.js/blob/master/docs/generated/interfaces/HttpRequest.html Retrieves the query string of the URL. ```APIDOC ## getQuery ### Description Retrieves the query string of the URL. ### Method Not applicable (this is a utility method). ### Endpoint Not applicable. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### UWS_HTTP_MAX_HEADERS_SIZE Environment Variable Source: https://github.com/unetworking/uwebsockets.js/blob/master/docs/generated/variables/EnvironmentVariables.UWS_HTTP_MAX_HEADERS_SIZE.html Configuration for the maximum total byte size of HTTP request headers. ```APIDOC ## Environment Variable: UWS_HTTP_MAX_HEADERS_SIZE ### Description Maximum total byte size of HTTP request headers. This is a runtime environment variable. ### Type `string | undefined` ### Default Value `4096` ### Usage This variable can be set at runtime to configure the header size limit. ### Example ```bash export UWS_HTTP_MAX_HEADERS_SIZE=8192 node your_app.js ``` ``` -------------------------------- ### us_socket Interface Source: https://github.com/unetworking/uwebsockets.js/blob/master/docs/generated/interfaces/us_socket.html Documentation for the us_socket interface representing a raw uSockets struct. ```APIDOC ## Interface us_socket ### Description Native type representing a raw uSockets struct us_socket_t. This interface is entirely unchecked and native; invalid usage may cause application instability. ### Definition Defined in index.d.ts:25 ``` -------------------------------- ### DEDICATED_DECOMPRESSOR_4KB Constant Source: https://github.com/unetworking/uwebsockets.js/blob/master/docs/generated/variables/DEDICATED_DECOMPRESSOR_4KB.html Documentation for the DEDICATED_DECOMPRESSOR_4KB constant used in CompressOptions. ```APIDOC ## DEDICATED_DECOMPRESSOR_4KB ### Description Sliding dedicated decompress window, requires 4KB of memory per socket (plus about 23KB). ### Type CompressOptions ### Definition Defined in index.d.ts:445 ``` -------------------------------- ### DEDICATED_COMPRESSOR_128KB Constant Source: https://github.com/unetworking/uwebsockets.js/blob/master/docs/generated/variables/DEDICATED_COMPRESSOR_128KB.html Documentation for the DEDICATED_COMPRESSOR_128KB constant used for socket compression settings. ```APIDOC ## DEDICATED_COMPRESSOR_128KB ### Description Represents a sliding dedicated compress window setting that requires 128KB of memory per socket. ### Type CompressOptions ### Definition Defined in index.d.ts:435 ``` -------------------------------- ### DEDICATED_COMPRESSOR_3KB Constant Source: https://github.com/unetworking/uwebsockets.js/blob/master/docs/generated/variables/DEDICATED_COMPRESSOR_3KB.html Documentation for the DEDICATED_COMPRESSOR_3KB constant used in compression options. ```APIDOC ## DEDICATED_COMPRESSOR_3KB ### Description Represents a sliding dedicated compress window setting. This configuration requires 3KB of memory per socket. ### Type CompressOptions ### Definition Defined in index.d.ts:423 ``` -------------------------------- ### missingServerName() Source: https://github.com/unetworking/uwebsockets.js/blob/master/docs/generated/interfaces/TemplatedApp.html Registers a synchronous callback that is triggered when server names are missing. Useful for handling requests with unknown hostnames. ```APIDOC ## POST /missingServerName ### Description Registers a synchronous callback on missing server names. See /examples/ServerName.js. ### Method POST ### Endpoint /missingServerName ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - **cb** ((hostname: string) => void) - Required - The callback function to execute when a server name is missing. ### Request Example ```json { "cb": "(hostname) => { console.log('Missing server name:', hostname); }" } ``` ### Response #### Success Response (200) - **TemplatedApp[]** - An array of TemplatedApp objects. #### Response Example ```json [ {} ] ``` ``` -------------------------------- ### DEDICATED_DECOMPRESSOR_8KB Configuration Source: https://github.com/unetworking/uwebsockets.js/blob/master/docs/generated/variables/DEDICATED_DECOMPRESSOR_8KB.html Information about the DEDICATED_DECOMPRESSOR_8KB setting, which configures a dedicated decompress window with specific memory requirements. ```APIDOC ## Variable DEDICATED_DECOMPRESSOR_8KB ### Description DEDICATED_DECOMPRESSOR_8KB is a configuration option for uWebSockets.js that enables a sliding dedicated decompress window. This setting requires 8KB of memory per socket, in addition to approximately 23KB. ### Type [CompressOptions](../types/CompressOptions.html) ### Defined in [index.d.ts:443](https://github.com/uNetworking/uWebSockets.js/blob/master/docs/index.d.ts#L443) ### Settings * **Member Visibility**: Protected, Inherited ``` -------------------------------- ### onDataV2 Source: https://github.com/unetworking/uwebsockets.js/blob/master/docs/generated/interfaces/HttpResponse.html V2 handler for reading HTTP request body data with preallocation support. ```APIDOC ## onDataV2 ### Description Handler for reading HTTP request body data. Provides maxRemainingBodyLength for preallocation. ### Parameters - **handler** (function) - Required - Callback function (chunk: ArrayBuffer, maxRemainingBodyLength: bigint) => void ### Returns - **HttpResponse** - The response object. ``` -------------------------------- ### trace Source: https://github.com/unetworking/uwebsockets.js/blob/master/docs/generated/interfaces/TemplatedApp.html Registers a handler for tracing requests matching a specified URL pattern. ```APIDOC ## trace ### Description Registers a handler for tracing requests that match the specified URL pattern. This is useful for debugging and monitoring. ### Method TRACE ### Endpoint /api/trace/{pattern} ### Parameters #### Path Parameters - **pattern** (RecognizedString) - Required - The URL pattern to match for trace requests. #### Query Parameters N/A #### Request Body - **handler** (function) - Required - The handler function to execute for trace requests. It receives HttpResponse and HttpRequest objects. ### Request Example ```javascript app.trace('/debug/:id', (res, req) => { // trace handler logic }); ``` ### Response #### Success Response (200) - **status** (string) - Indicates the handler was registered. #### Response Example ```json { "status": "registered" } ``` ``` -------------------------------- ### getUrl Source: https://github.com/unetworking/uwebsockets.js/blob/master/docs/generated/interfaces/HttpRequest.html Retrieves the URL. ```APIDOC ## getUrl ### Description Retrieves the URL. ### Method Not applicable (this is a utility method). ### Endpoint Not applicable. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### WebSocket API Source: https://github.com/unetworking/uwebsockets.js/blob/master/docs/generated/interfaces/TemplatedApp.html Registers a handler for WebSocket upgrade requests matching a specified URL pattern. ```APIDOC ## POST /ws ### Description Registers a handler matching specified URL pattern where WebSocket upgrade requests are caught. ### Method POST ### Endpoint /ws ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **pattern** (RecognizedString) - Required - The URL pattern to match for WebSocket upgrades. - **behavior** (WebSocketBehavior) - Required - The WebSocket behavior configuration. ### Request Example ```json { "pattern": "/chat", "behavior": { "open": "(ws) => { ... }", "message": "(ws, message) => { ... }" } } ``` ### Response #### Success Response (200) - **TemplatedApp[]** - Returns an array of TemplatedApp instances. #### Response Example ```json [ { "app": "instance1" }, { "app": "instance2" } ] ``` ``` -------------------------------- ### getTopics Source: https://github.com/unetworking/uwebsockets.js/blob/master/docs/generated/interfaces/WebSocket.html Retrieves a list of all topics the current WebSocket connection is subscribed to. ```APIDOC ## getTopics ### Description Returns a list of topics this WebSocket is subscribed to. ### Method GET (Implicit) ### Endpoint N/A (Method on WebSocket instance) ### Returns - **string[]**: An array of topic strings. ### Returns Example ``` // Example usage (conceptual) const topics = ws.getTopics(); ``` ``` -------------------------------- ### Subscribe to Topic Source: https://github.com/unetworking/uwebsockets.js/blob/master/docs/generated/interfaces/WebSocket.html Subscribes the WebSocket connection to a specified topic. Returns a boolean indicating success. ```typescript subscribe(topic: RecognizedString): boolean; ``` -------------------------------- ### subscribe Source: https://github.com/unetworking/uwebsockets.js/blob/master/docs/generated/interfaces/WebSocket.html Subscribe to a topic. Returns true on success, if the WebSocket was subscribed. ```APIDOC ## subscribe ### Description Subscribe to a topic. Returns true on success, if the WebSocket was subscribed. ### Method N/A (This appears to be a function signature, not a REST endpoint) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **topic** (RecognizedString) - Required - The topic to subscribe to. ### Request Example ```json { "topic": "news" } ``` ### Response #### Success Response (Boolean) * **Return Value** (boolean) - True on success, if the WebSocket was subscribed. #### Response Example ```json true ``` ``` -------------------------------- ### pause / resume Source: https://github.com/unetworking/uwebsockets.js/blob/master/docs/generated/interfaces/HttpResponse.html Flow control methods for HTTP request body streaming. ```APIDOC ## pause ### Description Pause HTTP request body streaming (throttle). ## resume ### Description Resume HTTP request body streaming (unthrottle). ``` -------------------------------- ### Optimize Response Writing with cork Source: https://github.com/unetworking/uwebsockets.js/blob/master/docs/generated/interfaces/HttpResponse.html Use cork to batch multiple write operations into a single atomic IO operation, improving performance for both TCP and TLS connections. ```javascript res.cork(() => { res.writeStatus("200 OK").writeHeader("Some", "Value").write("Hello world!");}); ``` -------------------------------- ### onWritable Source: https://github.com/unetworking/uwebsockets.js/blob/master/docs/generated/interfaces/HttpResponse.html Registers a handler for writable events to manage backpressure. ```APIDOC ## onWritable ### Description Registers a handler for writable events. Used to continue failed write attempts. ### Parameters - **handler** (function) - Required - Callback function (offset: number) => boolean ### Returns - **HttpResponse** - The response object. ``` -------------------------------- ### write Source: https://github.com/unetworking/uwebsockets.js/blob/master/docs/generated/interfaces/HttpResponse.html Writes a chunk of data to the response. ```APIDOC ## write ### Description Enters or continues chunked encoding mode. Writes part of the response. End with zero length write. ### Parameters - **chunk** (RecognizedString) - Required - The data chunk to write. ### Response - **Returns** (boolean) - Returns true if no backpressure was added. ``` -------------------------------- ### TRACE API Source: https://github.com/unetworking/uwebsockets.js/blob/master/docs/generated/interfaces/TemplatedApp.html Registers an HTTP TRACE handler matching a specified URL pattern. ```APIDOC ## POST /trace ### Description Registers an HTTP TRACE handler matching specified URL pattern. ### Method POST ### Endpoint /trace ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **pattern** (RecognizedString) - Required - The URL pattern to match. - **handler** ((res: HttpResponse, req: HttpRequest) => void | Promise) - Required - The handler function to execute for TRACE requests. ### Request Example ```json { "pattern": "/trace-path", "handler": "(res, req) => { /* handler logic */ }" } ``` ### Response #### Success Response (200) - **TemplatedApp[]** - Returns an array of TemplatedApp instances. #### Response Example ```json [ { "app": "instance1" }, { "app": "instance2" } ] ``` ``` -------------------------------- ### HTTP POST Handler Source: https://github.com/unetworking/uwebsockets.js/blob/master/docs/generated/interfaces/TemplatedApp.html Registers an HTTP POST handler for a specified URL pattern. ```APIDOC ## POST /:pattern ### Description Registers an HTTP POST handler matching the specified URL pattern. ### Method POST ### Endpoint /:pattern ### Parameters #### Path Parameters - **pattern** (RecognizedString) - Required - The URL pattern to match. #### Request Body - **handler** ((res: HttpResponse, req: HttpRequest) => void | Promise) - Required - The handler function to execute. ### Response #### Success Response (200) - **TemplatedApp** - Returns the TemplatedApp instance for chaining. #### Response Example (No specific example provided in the source text for the response body, but the return type is TemplatedApp.) ``` -------------------------------- ### WebSocket Compression Setting Source: https://github.com/unetworking/uwebsockets.js/blob/master/docs/generated/interfaces/WebSocketBehavior.html Configures the permessage-deflate compression level. Options include uWS.DISABLED, uWS.SHARED_COMPRESSOR, or specific uWS.DEDICATED_COMPRESSOR_xxxKB values. Defaults to uWS.DISABLED. ```typescript compression?: number; ``` -------------------------------- ### WebSocket Connection Management Source: https://github.com/unetworking/uwebsockets.js/blob/master/docs/generated/interfaces/WebSocket.html Methods for controlling the lifecycle of a WebSocket connection, including closing and checking buffer status. ```APIDOC ## close() ### Description Forcefully closes this WebSocket. Immediately calls the close handler. No WebSocket close message is sent. ### Returns - **void** ## end(code, shortMessage) ### Description Gracefully closes this WebSocket. Immediately calls the close handler. A WebSocket close message is sent with code and shortMessage. ### Parameters - **code** (number) - Optional - The close status code. - **shortMessage** (RecognizedString) - Optional - The close message. ### Returns - **void** ## getBufferedAmount() ### Description Returns the bytes buffered in backpressure. This is similar to the bufferedAmount property in the browser counterpart. ### Returns - **number** - The amount of buffered bytes. ``` -------------------------------- ### setYield Source: https://github.com/unetworking/uwebsockets.js/blob/master/docs/generated/interfaces/HttpRequest.html Sets the yield behavior. ```APIDOC ## setYield ### Description Sets the yield behavior. ### Method Not applicable (this is a utility method). ### Endpoint Not applicable. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### send Source: https://github.com/unetworking/uwebsockets.js/blob/master/docs/generated/interfaces/WebSocket.html Sends a message to the connected client. Handles backpressure management. ```APIDOC ## send ### Description Sends a message to the connected client. Returns 1 for success, 2 for dropped due to backpressure limit, and 0 for built up backpressure that will drain over time. You can check backpressure before or after sending by calling getBufferedAmount(). ### Method POST (Implicit) ### Endpoint N/A (Method on WebSocket instance) ### Parameters #### Path Parameters - **message** (RecognizedString) - Required - The message to send. #### Query Parameters - **isBinary** (boolean) - Optional - Whether the message is binary. - **compress** (boolean) - Optional - Whether to compress the message. ### Returns - **number**: A status code indicating the send result (1: success, 2: dropped, 0: backpressure). ### Request Example ```javascript // Example usage (conceptual) const sendStatus = ws.send('Hello client!'); ``` ``` -------------------------------- ### getHeader Source: https://github.com/unetworking/uwebsockets.js/blob/master/docs/generated/interfaces/HttpRequest.html Retrieves a specific HTTP header. ```APIDOC ## getHeader ### Description Retrieves a specific HTTP header. ### Method Not applicable (this is a utility method). ### Endpoint Not applicable. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### writeHeader Source: https://github.com/unetworking/uwebsockets.js/blob/master/docs/generated/interfaces/HttpResponse.html Writes a header key and value to the HTTP response. ```APIDOC ## writeHeader ### Description Writes key and value to HTTP response. ### Parameters - **key** (RecognizedString) - Required - The header key. - **value** (RecognizedString) - Required - The header value. ### Response - **Returns** (HttpResponse) ``` -------------------------------- ### onData Source: https://github.com/unetworking/uwebsockets.js/blob/master/docs/generated/interfaces/HttpResponse.html Handler for reading HTTP request body data chunks. ```APIDOC ## onData ### Description Handler for reading HTTP request body data. Must be attached before asynchronous operations. ### Parameters - **handler** (function) - Required - Callback function (chunk: ArrayBuffer, isLast: boolean) => void ### Returns - **HttpResponse** - The response object. ``` -------------------------------- ### DEDICATED_COMPRESSOR_8KB Constant Source: https://github.com/unetworking/uwebsockets.js/blob/master/docs/generated/variables/DEDICATED_COMPRESSOR_8KB.html Details regarding the DEDICATED_COMPRESSOR_8KB constant used for socket compression configuration. ```APIDOC ## DEDICATED_COMPRESSOR_8KB ### Description Represents a sliding dedicated compression window that requires 8KB of memory per socket. ### Type CompressOptions ### Definition Defined in index.d.ts:427 ``` -------------------------------- ### AppDescriptor Interface Source: https://github.com/unetworking/uwebsockets.js/blob/master/docs/generated/interfaces/AppDescriptor.html The AppDescriptor is a native type representing a raw uWebSockets struct, primarily used for distributing work across worker threads. It is an unchecked interface, meaning invalid usage can lead to application instability. ```APIDOC ## Interface AppDescriptor ### Description Native type representing a raw uWebSockets struct AppDescriptor. Used internally for worker thread distribution. Careful with this one, it is entirely unchecked and native so invalid usage will blow up. * Defined in [index.d.ts:39](https://github.com/uNetworking/uWebSockets.js/blob/master/docs/index.d.ts#L39) ### Settings Member Visibility * Protected * Inherited ThemeOSLightDark ``` -------------------------------- ### getCaseSensitiveMethod Source: https://github.com/unetworking/uwebsockets.js/blob/master/docs/generated/interfaces/HttpRequest.html Retrieves the HTTP method with case sensitivity. ```APIDOC ## getCaseSensitiveMethod ### Description Retrieves the HTTP method with case sensitivity. ### Method Not applicable (this is a utility method). ### Endpoint Not applicable. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### Interface us_socket_context_t Source: https://github.com/unetworking/uwebsockets.js/blob/master/docs/generated/interfaces/us_socket_context_t.html Details regarding the us_socket_context_t native type used in uWebSockets.js. ```APIDOC ## Interface us_socket_context_t ### Description Native type representing a raw uSockets struct us_socket_context_t. This interface is used while upgrading a WebSocket manually. ### Definition Defined in index.d.ts:31 ``` -------------------------------- ### domain(domain: string) Source: https://github.com/unetworking/uwebsockets.js/blob/master/docs/generated/interfaces/TemplatedApp.html Registers a scope for SNI domains. Used in conjunction with route handlers to attach them to specific domains. ```APIDOC ## domain(domain: string) ### Description Browse to SNI domain. Used together with .get, .post and similar to attach routes under SNI domains. ### Parameters #### Path Parameters - **domain** (string) - Required - The domain name to scope subsequent routes. ``` -------------------------------- ### close Source: https://github.com/unetworking/uwebsockets.js/blob/master/docs/generated/interfaces/TemplatedApp.html Closes all sockets, forcefully terminating all connections. ```APIDOC ## close ### Description Closes all active sockets, including listen sockets. This action will forcefully terminate all ongoing connections. ### Method POST ### Endpoint /api/close ### Parameters N/A ### Request Example ```json { "action": "close_all_connections" } ``` ### Response #### Success Response (200) - **message** (string) - Confirmation that all sockets have been closed. #### Response Example ```json { "message": "All connections terminated." } ``` ``` -------------------------------- ### WebSocket Performance Optimization Source: https://github.com/unetworking/uwebsockets.js/blob/master/docs/generated/interfaces/WebSocket.html Method for optimizing network syscalls by grouping multiple send operations. ```APIDOC ## cork(cb) ### Description Takes a function in which the socket is corked (packing many sends into one single syscall/SSL block). ### Parameters - **cb** (function) - Required - The callback function containing the send operations. ### Returns - **WebSocket** - The current WebSocket instance. ```