You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
It's probably a good idea to stick to something like this:
importWebSocketfrom'ws';import{createServer}from'http';constserver=createServer();constwss=newWebSocketServer({noServer: true});server.on('upgrade',functionupgrade(request,socket,head){// This function is not defined on purpose. Implement it with your own logic.authenticate(request,(err,client)=>{if(err||!client){socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n');socket.destroy();return;}wss.handleUpgrade(request,socket,head,functiondone(ws){// You are done. `ws` is your `WebSocket` instance, you can do// whatever you want with it.});});});server.listen(8080);
consthttp=require('http');constWebSocket=require('ws');constserver=http.createServer();constwss=newWebSocket.Server({noServer: true});wss.on('connection',functionconnection(ws,request, ...args){// ...});server.on('upgrade',asyncfunctionupgrade(request,socket,head){// Do what you normally do in `verifyClient()` here and then use// `WebSocketServer.prototype.handleUpgrade()`.letargs;try{args=awaitgetDataAsync();}catch(e){socket.destroy();return;}wss.handleUpgrade(request,socket,head,functiondone(ws){wss.emit('connection',ws,request, ...args);});});server.listen(8080);
The text was updated successfully, but these errors were encountered:
const{ WebSocketServer }=require('ws');constwss=newWebSocketServer({port: 8080,verifyClient: async({ req },cb)=>{const{ headers }=req;if(headers.token){constdecodedToken=awaitdecodeToken(headers.token);// req.headers.decodedToken = JSON.stringify(decodedToken);// As noted. The token can just as well be added directly to reqreq.decodedToken=JSON.stringify(decodedToken);cb(true);}else{cb(false,401,'Unauthorized');}}});wss.on('connection',(ws,req)=>{console.log("on Connection decodedToken ==> ",JSON.parse(req.decodedToken));});
Need expansion in the if (headers.token) block. Error handling, wrapping in try / catch or chaining.
Repository owner
locked and limited conversation to collaborators
Mar 22, 2022
It's probably a good idea to stick to something like this:
as discussed in websockets#1966 (comment)
Same discussion, just older: websockets#377 (comment)
The text was updated successfully, but these errors were encountered: