Skip to content

Commit

Permalink
feat: forward cookies to websocket proxy (#245)
Browse files Browse the repository at this point in the history
  • Loading branch information
morenol authored Apr 30, 2022
1 parent 9752690 commit 302b9f7
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 5 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`

Expand Down
10 changes: 9 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
9 changes: 6 additions & 3 deletions test/websocket.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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')

Expand Down

0 comments on commit 302b9f7

Please sign in to comment.