diff --git a/README.md b/README.md index 6f4c67b..669aaa4 100644 --- a/README.md +++ b/README.md @@ -156,7 +156,7 @@ This module has _partial_ support for forwarding websockets by passing a [`@fastify/websocket`](https://github.com/fastify/fastify-websocket). A few things are missing: -1. forwarding headers as well as `rewriteHeaders` +1. forwarding headers as well as `rewriteHeaders`. Note: Only cookie headers are being forwarded 2. request id logging 3. support `ignoreTrailingSlash` diff --git a/index.js b/index.js index ad9d6c3..51a8178 100644 --- a/index.js +++ b/index.js @@ -90,9 +90,17 @@ function setupWebSocketProxy (fastify, options, rewritePrefix) { return } + let optionsWs = {} + if (request.headers.cookie) { + const headers = { cookie: request.headers.cookie } + optionsWs = { ...options.wsClientOptions, headers } + } else { + optionsWs = options.wsClientOptions + } + const url = createWebSocketUrl(request) - const target = new WebSocket(url, options.wsClientOptions) + const target = new WebSocket(url, optionsWs) fastify.log.debug({ url: url.href }, 'proxy websocket') proxyWebSockets(source, target) diff --git a/test/websocket.js b/test/websocket.js index 0e19a73..128e713 100644 --- a/test/websocket.js +++ b/test/websocket.js @@ -7,16 +7,18 @@ const WebSocket = require('ws') const { createServer } = require('http') const { promisify } = require('util') const { once } = require('events') +const cookieValue = 'foo=bar' test('basic websocket proxy', async (t) => { - t.plan(2) + t.plan(3) 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) => { + wss.on('connection', (ws, request) => { + t.equal(request.headers.cookie, cookieValue) ws.on('message', (message) => { t.equal(message.toString(), 'hello') // echo @@ -35,7 +37,8 @@ test('basic websocket proxy', async (t) => { await server.listen(0) t.teardown(server.close.bind(server)) - const ws = new WebSocket(`ws://localhost:${server.server.address().port}`) + const options = { headers: { cookie: cookieValue } } + const ws = new WebSocket(`ws://localhost:${server.server.address().port}`, options) await once(ws, 'open')