How would I pass a jwt from my redux store into my middleware that then sends a socket.io connect request to my backend?
In my React App, I initialize my websocket (using socketIO) via middleware, and then want to validate the socket connection with a JWT I retrieve from Auth0.
My backend middleware keeps getting null when I read the handshake. This leads me to believe that I haven’t yet recieved my token, so I’ve tried setting up a promise, with different configurations, but to no avail.
I would like to useSelector() but it’s not really a functional component, and I don’t know if I could use this with middleware.
Do I use a cb() in the io.( URL, { auth:{token: (cb) { token: 'abc' } } } );
?
Code below:
middleware.tsx
const notificationMiddleware: Middleware = store => {
let socket: Socket;
const state = store.getState();
let token:string|null = null;
const tokenPromise = new Promise((resolve,reject)=>{
token = state.auth.token;
if(token !== null){
resolve(token)
}
});
tokenPromise.then((result)=>{
console.log('Finished: ', result);
})
return next => action => {
const isConnectionEsablished = socket && store.getState().notification.isConnected;
if(notificationActions.startConnecting.match(action) && !isConnectionEsablished && token !== null){
socket = io(process.env.REACT_APP_SERVER_URL, {withCredentials: true, auth: {token: token } });
store.dispatch(notificationActions.connectionEstablished());
console.warn('WebSockets connect');
socket.on('connect', () => {
});
socket.on('message', (res) => {
console.info('Notification recieved, storing.', res)
store.dispatch(notificationActions.receiveMessage(res));
});
socket.on('job', (res) => {
console.info('job recieved, ', res);
store.dispatch(socketJobPayload(res));
});
socket.on('indv', (res) => {
console.info('indv event recieved, ', res);
//send individual object
store.dispatch(socketIndividualPayload(res.data));
store.dispatch(socketJobMetrics(res.data));
store.dispatch(socketEmployerMetrics(res.data.ieMetrics));
//send metrics to job
});
socket.on("connect_error", (err) => {
console.log(err.message); // prints the message associated with the error
});
}
next(action);
}
}
export default notificationMiddleware;
backend, if it matters
io.use( async(socket:any, next:any) => {
try{
const token = socket.handshake.auth.token;
console.log(token);
if(token === 'token-pass'){
console.log('socket passed!')
next();
}else{
next(new Error("thou shall not pass!"));
}
}catch(e){
console.log(e);
}
});