Last modified: Jul 21, 2025 By Alexander Williams
Install Socket.io in Node.js - Quick Guide
Socket.io is a popular library for real-time web applications. It enables bidirectional communication between clients and servers. This guide will show you how to install and use it in Node.js.
Prerequisites
Before installing Socket.io, ensure you have Node.js installed. You can check by running node -v
in your terminal.
node -v
v18.12.1
If you don't have Node.js, download it from the official website. You might also want to check our guide on installing TypeScript in Node.js for related setups.
Install Socket.io
To install Socket.io, open your terminal and navigate to your project directory. Run the following command:
npm install socket.io
This will add Socket.io to your project's dependencies. For production use, you might want to save it as a dependency.
Basic Socket.io Setup
Here's a simple example to set up a Socket.io server. Create a file named server.js and add this code:
const express = require('express');
const app = express();
const http = require('http').createServer(app);
const io = require('socket.io')(http);
io.on('connection', (socket) => {
console.log('a user connected');
});
http.listen(3000, () => {
console.log('listening on *:3000');
});
This code creates a basic server that logs when a user connects. The io.on
method listens for new connections.
Client-Side Setup
For the client side, include the Socket.io client library. Add this script to your HTML file:
<script src="/socket.io/socket.io.js"></script>
<script>
const socket = io();
</script>
This connects the client to your Socket.io server. The client will automatically try to connect to the host serving the page.
Testing the Connection
Start your server with node server.js
. Open your browser and check the console. You should see "a user connected" in your terminal.
For more advanced setups, you might want to explore Next.js installation or React installation guides.
Handling Events
Socket.io works by emitting and listening to events. Here's an example of sending and receiving messages:
// Server-side
io.on('connection', (socket) => {
socket.on('chat message', (msg) => {
io.emit('chat message', msg);
});
});
// Client-side
socket.emit('chat message', 'Hello world');
socket.on('chat message', (msg) => {
console.log('message: ' + msg);
});
This creates a simple chat system. The emit
method sends events, while on
listens for them.
Conclusion
Socket.io is powerful for real-time applications. You've learned how to install it and set up basic communication. For more Node.js guides, check our other tutorials.
Remember to handle errors and disconnect events in production. Happy coding with Socket.io and Node.js!