Skip to content

Commit 302b9f7

Browse files
authored
feat: forward cookies to websocket proxy (#245)
1 parent 9752690 commit 302b9f7

File tree

3 files changed

+16
-5
lines changed

3 files changed

+16
-5
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -156,7 +156,7 @@ This module has _partial_ support for forwarding websockets by passing a
156156
[`@fastify/websocket`](https://github.com/fastify/fastify-websocket).
157157
A few things are missing:
158158

159-
1. forwarding headers as well as `rewriteHeaders`
159+
1. forwarding headers as well as `rewriteHeaders`. Note: Only cookie headers are being forwarded
160160
2. request id logging
161161
3. support `ignoreTrailingSlash`
162162

index.js

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -90,9 +90,17 @@ function setupWebSocketProxy (fastify, options, rewritePrefix) {
9090
return
9191
}
9292

93+
let optionsWs = {}
94+
if (request.headers.cookie) {
95+
const headers = { cookie: request.headers.cookie }
96+
optionsWs = { ...options.wsClientOptions, headers }
97+
} else {
98+
optionsWs = options.wsClientOptions
99+
}
100+
93101
const url = createWebSocketUrl(request)
94102

95-
const target = new WebSocket(url, options.wsClientOptions)
103+
const target = new WebSocket(url, optionsWs)
96104

97105
fastify.log.debug({ url: url.href }, 'proxy websocket')
98106
proxyWebSockets(source, target)

test/websocket.js

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,16 +7,18 @@ const WebSocket = require('ws')
77
const { createServer } = require('http')
88
const { promisify } = require('util')
99
const { once } = require('events')
10+
const cookieValue = 'foo=bar'
1011

1112
test('basic websocket proxy', async (t) => {
12-
t.plan(2)
13+
t.plan(3)
1314

1415
const origin = createServer()
1516
const wss = new WebSocket.Server({ server: origin })
1617
t.teardown(wss.close.bind(wss))
1718
t.teardown(origin.close.bind(origin))
1819

19-
wss.on('connection', (ws) => {
20+
wss.on('connection', (ws, request) => {
21+
t.equal(request.headers.cookie, cookieValue)
2022
ws.on('message', (message) => {
2123
t.equal(message.toString(), 'hello')
2224
// echo
@@ -35,7 +37,8 @@ test('basic websocket proxy', async (t) => {
3537
await server.listen(0)
3638
t.teardown(server.close.bind(server))
3739

38-
const ws = new WebSocket(`ws://localhost:${server.server.address().port}`)
40+
const options = { headers: { cookie: cookieValue } }
41+
const ws = new WebSocket(`ws://localhost:${server.server.address().port}`, options)
3942

4043
await once(ws, 'open')
4144

0 commit comments

Comments
 (0)