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
- Header Check: Checks the
connection
andupgrade
headers to determine if the request is an upgrade attempt. - Path Validation: Compares the request path against the configured WebSocket paths (default:
/ws
). - Upgrade Attempt: Calls
server.upgrade
to perform the WebSocket upgrade, attaching the HTTP context and setting a secure cookie. - 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.
- If successful, returns
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.