Skip to content

UpgradeMiddleware

This file defines the UpgradeMiddleware class, which is responsible for handling HTTP-to-WebSocket upgrade requests in the @sodacore/core WebSocket (WS) module. It checks incoming HTTP requests for upgrade headers, validates the request path, and performs the upgrade to a WebSocket connection if all conditions are met.


Features

  • Upgrade Detection: Inspects HTTP headers to determine if the request is attempting to upgrade to a WebSocket connection.
  • Path Validation: Validates that the request path matches the configured WebSocket endpoint(s).
  • WebSocket Upgrade: Performs the upgrade using Bun's server API, attaching the HTTP context and setting a session cookie.
  • Logging: Logs upgrade attempts for monitoring and debugging.
  • Error Handling: Returns appropriate HTTP responses if the upgrade is not implemented or fails.

Usage

This middleware is automatically registered and used by the Sodacore WebSocket module. You can customize the WebSocket endpoint path(s) via the configuration.

typescript
import UpgradeMiddleware from './middleware/upgrade';

// Registered automatically, but can be used in custom setups if needed

API

Constructor

  • No explicit constructor; uses dependency injection for configuration and logger.

Methods

async handle(context: HttpContext): Promise<Response | boolean | void>

  • context: The current HTTP context.
  • Returns:
    • true if the upgrade was successful (prevents further HTTP response).
    • Response with status 501 if the path is not implemented.
    • Response with status 500 if the upgrade fails.
    • void if the request is not an upgrade attempt.

How It Works

  1. Header Check: Checks the connection and upgrade headers to determine if the request is an upgrade attempt.
  2. Path Validation: Compares the request path against the configured WebSocket paths (default: /ws).
  3. Upgrade Attempt: Calls server.upgrade to perform the WebSocket upgrade, attaching the HTTP context and setting a secure cookie.
  4. Result Handling:
    • If successful, returns true to halt further HTTP processing.
    • If the path is invalid, returns a 501 response.
    • If the upgrade fails, returns a 500 response.

Notes

  • The middleware uses dependency injection to access configuration and logging.
  • The session cookie (sodacoreId) is set for tracking and security.
  • Designed for use with Bun's HTTP and WebSocket server APIs.
  • Only requests with the correct headers and matching paths will be upgraded.

Released under the Apache-2.0 License.