Created
June 9, 2018 19:40
-
-
Save rafaelsales/fcf1f93b75462fb92c04da0fee9ff99b to your computer and use it in GitHub Desktop.
node websockets proxy with session
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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