[Fixed] How to handle io.use middleware to capture errors on client?


I need to check authentication for my socket connection and drop one if they failed. My server and client codes looks like the following;

// server.js

var http = require('http');
var sio = require('socket.io');
var app = require('express')();

var server = require('http').createServer(app).listen(3000, function () {
    console.log('Server listening on 3000 port');

var io = sio.listen(server);

io.use(function (socket, next) { 
    return next(new Error('Not Authenticated'));

// client.js

var socket = io.connect(window.location.origin);

socket.on('connect', function () {
    console.log('socket connected')

My problem is I can’t capture Not Authenticated error on the client side to handle it and show some popup for example.

Now if Not Authenticated error get executed on server side then socket connection still persists but none of socket.emit('message') don’t any work.

How can I capture this error on client side to make some decision?


You should catch error events clientside:

socket.on('error', function(err) {
  console.log('The server sent an error', err);

2021 update: for Socket.io v3 and up, errors that get passed to middleware callbacks trigger a connect_error event client side, as documented here.

Leave a Reply

(*) Required, Your email will not be published