Express Socket.io Middleware
This middleware allows you to use the existing HTTP REST API as a WebSocket.
Installation
The easiest way to install express-socket.io-middleware
is with npm.
npm install express-socket.io-middleware
Alternately, download the source.
git clone https://github.com/stegano/express-socket.io-middleware.git
Example
This middleware allows you to process all rest api requests and responses implemented as websockets.
Server
...
const app = express();
const server = http.createServer(app);
const io = new Server(server, {
path: '/ws',
});
app
.use(socketIoMiddleware(io, 'http://localhost:3000', 'secret!'))
.get('/test', (_, res) => {
res.send({message: 'Hello World'})
});
server.listen(3000);
...
Clients
- You can change the event name in configuration. Please check the Configuration section.
Client With Socket.io
Request through websocket and receive a response
const socket = io({
path: '/ws',
transports: ['websocket']
});
socket.emit('request', {
pathanme: '/test',
method: 'GET',
data: {},
params: {}
});
socket.on('response', (data) => {
console.log(data);
});
Client With HTTP API and Socket.io
Request using REST API and receive response using WebSocket
const socket = io({
path: '/ws',
transports: ['websocket']
});
socket.on('token', ({token}) => {
axios.get('/test', {
headers: {
authorization: `Bearer ${token}`
}
})
});
socket.on('response', (data) => {
console.log(data);
});
Configuration
unexpectedErrorMessage?: string
transformResponsePayload?: (data: ResponsePayload) => any
eventNames?: {
token?: string
request?: string
response?: string
}
__advanced__?: {
httpKeepAlive?: boolean
axiosRequestConfig?: AxiosRequestConfig
}
Internal Implementation
This middleware internally sends an HTTP request to the web server and sends the received response value to the connected web socket.