Skip to content

Instantly share code, notes, and snippets.

@rafaelsales
Created June 9, 2018 19:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rafaelsales/fcf1f93b75462fb92c04da0fee9ff99b to your computer and use it in GitHub Desktop.
Save rafaelsales/fcf1f93b75462fb92c04da0fee9ff99b to your computer and use it in GitHub Desktop.
node websockets proxy with session
@dougwilson thanks for the quick response. Yeah, I've read most of the session lib source and couldn't see a reason for it not work.
I found a way, by manually calling session on the express websockets upgrade request handler:
```js
import Express from 'express'
import ExpressSession from 'express-session'
import proxy from 'http-proxy-middleware'
const session = ExpressSession({ ... })
const websocketsProxy = proxy('/websockets', {
target: CONFIG.backendServerURL,
changeOrigin: true,
ws: true,
onProxyReqWs: (proxyReq, req, socket) => {
proxyReq.setHeader('Authorization', `Bearer ${req.session.accessToken}`)
},
})
const app = Express()
app.use(session) // Handles creating/reading session in normal HTTP requests
const server app.listen(PORT)
server.on('upgrade', (req, socket) => {
// The only thing I dislike is passing the empty `{}` object as a fake `response`
// object, which the session object shouldn't need here
session(req, {}, () => {
// Calls proxy when req.session is already present
websocketsProxy.upgrade(req, socket)
})
})
```
Can you think of way of doing this that looks less hacky?
Thanks!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment