Can't emit to client during middleware without ending it with next #3820
Unanswered
lambertkevin
asked this question in
Q&A
Replies: 1 comment 1 reply
-
You can send the error to the client: const middleware = (socket, next) => {
try {
const { token } = socket.handshake.auth;
jwt.verify(token, process.env.SERVICE_JWT_SECRET);
socket.handshake.decodedToken = jwt.decode(token);
next();
} catch (error) {
if (error.name === 'TokenExpiredError') {
next(new Error('TokenExpiredError'));
} else {
// handle other errors (but always call next)
}
}
} And handle it on the client: socket.on('connect_error', (err) => {
if (err.name === 'TokenExpiredError') {
// refresh token, and then try to reconnect
socket.connect();
}
}); Documentation: https://socket.io/docs/v3/middlewares/#Handling-middleware-error |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
I'm implementing a simple middleware with socket.io
3.1.1
and looking for a way to allow a request to wait for a refreshed accessToken before sending an error.My attempts have been unsuccessful as it looks like I can't emit an event to my client (asking him to refresh its token and sending it back) without ending the middleware lifecycle with
next
.Here is a simplified version of the middleware:
It looks like emitting any event to the client without using
next
is never sent and I would like to avoid disconnecting and reconnecting.Is there a way to do this that I'm missing ?
Beta Was this translation helpful? Give feedback.
All reactions