Skip to content

feat: allow configuring handleProtocols or change default behavior #176

@productdevbook

Description

@productdevbook

Problem

The node adapter hardcodes handleProtocols: () => false:

// src/adapters/node.ts
const wss = options.wss || new _WebSocketServer({
  noServer: true,
  handleProtocols: () => false,
  ...options.serverOptions
});

This breaks WebSocket subprotocol negotiation for browsers. When using protocols like graphql-transport-ws (for GraphQL subscriptions), browsers reject the connection:

WebSocket connection failed: Error during WebSocket handshake: 
Sent non-empty 'Sec-WebSocket-Protocol' header but no response was received

Why This Happens

  1. Browser sends Sec-WebSocket-Protocol: graphql-transport-ws
  2. ws library calls handleProtocols() → returns false
  3. ws internally marks "no protocol selected"
  4. Even if we add Sec-WebSocket-Protocol header in the headers event, browsers still reject
  5. Node.js ws client is lenient and accepts, but browsers are strict

Current Workaround Doesn't Work for Browsers

defineWebSocketHandler({
  upgrade(request) {
    const protocol = request.headers.get('sec-websocket-protocol')
    if (protocol?.includes('graphql-transport-ws')) {
      return {
        headers: { 'Sec-WebSocket-Protocol': 'graphql-transport-ws' }
      }
    }
  }
})

This works for Node.js clients but not for browsers.

Proposed Solutions

Option 1: Smart default based on upgrade hook response

If the upgrade hook returns a Sec-WebSocket-Protocol header, use that as the selected protocol:

handleProtocols: (protocols, request) => {
  // Check if upgrade hook set a protocol header
  const upgradeProtocol = request._upgradeHeaders?.get?.('sec-websocket-protocol')
  if (upgradeProtocol && protocols.has(upgradeProtocol)) {
    return upgradeProtocol
  }
  return false
}

Option 2: Allow configuration via options

wsAdapter({
  serverOptions: {
    handleProtocols: (protocols) => {
      if (protocols.has('graphql-transport-ws')) return 'graphql-transport-ws'
      return false
    }
  }
})

This already works via ...options.serverOptions spread, but requires upstream (Nitro) to expose it.

Option 3: Echo back first requested protocol by default

Instead of () => false, default to echoing the first protocol:

handleProtocols: (protocols) => protocols.values().next().value || false

Use Case

GraphQL subscriptions using the graphql-ws protocol, which is standard for:

Environment

  • crossws: 0.4.1
  • ws: 8.x
  • Tested with Chrome, Firefox, Safari - all fail
  • Node.js ws client works (more lenient)

Related

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions