Skip to content

Commit

Permalink
Pass WebSocket subprotocol to upstream (#256)
Browse files Browse the repository at this point in the history
  • Loading branch information
yoursunny authored Jun 27, 2022
1 parent 2ffab3d commit 17ac3a2
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 4 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,7 @@ A few things are missing:
1. forwarding headers as well as `rewriteHeaders`. Note: Only cookie headers are being forwarded
2. request id logging
3. support `ignoreTrailingSlash`
4. forwarding more than one subprotocols. Note: Only the first subprotocol is being forwarded

Pull requests are welcome to finish this feature.

Expand Down
7 changes: 6 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,11 @@ function setupWebSocketProxy (fastify, options, rewritePrefix) {
return
}

const subprotocols = []
if (source.protocol) {
subprotocols.push(source.protocol)
}

let optionsWs = {}
if (request.headers.cookie) {
const headers = { cookie: request.headers.cookie }
Expand All @@ -100,7 +105,7 @@ function setupWebSocketProxy (fastify, options, rewritePrefix) {

const url = createWebSocketUrl(request)

const target = new WebSocket(url, optionsWs)
const target = new WebSocket(url, subprotocols, optionsWs)

fastify.log.debug({ url: url.href }, 'proxy websocket')
proxyWebSockets(source, target)
Expand Down
7 changes: 4 additions & 3 deletions test/websocket.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,18 @@ const { createServer } = require('http')
const { promisify } = require('util')
const { once } = require('events')
const cookieValue = 'foo=bar'
const subprotocolValue = 'foo-subprotocol'

test('basic websocket proxy', async (t) => {
t.plan(3)
t.plan(4)

const origin = createServer()
const wss = new WebSocket.Server({ server: origin })
t.teardown(wss.close.bind(wss))
t.teardown(origin.close.bind(origin))

wss.on('connection', (ws, request) => {
t.equal(ws.protocol, subprotocolValue)
t.equal(request.headers.cookie, cookieValue)
ws.on('message', (message) => {
t.equal(message.toString(), 'hello')
Expand All @@ -38,7 +40,7 @@ test('basic websocket proxy', async (t) => {
t.teardown(server.close.bind(server))

const options = { headers: { cookie: cookieValue } }
const ws = new WebSocket(`ws://localhost:${server.server.address().port}`, options)
const ws = new WebSocket(`ws://localhost:${server.server.address().port}`, [subprotocolValue], options)

await once(ws, 'open')

Expand All @@ -47,7 +49,6 @@ test('basic websocket proxy', async (t) => {
stream.write('hello')

const [buf] = await once(stream, 'data')

t.equal(buf.toString(), 'hello')

await Promise.all([
Expand Down

0 comments on commit 17ac3a2

Please sign in to comment.