Overview
Add real-time capabilities to your app. Perfect for chat, live updates, and collaborative features.
Features
- Socket.io integration with Express
- Optional JWT authentication
- Room management helpers
- Connection/disconnection handlers
Installation
npx hanma add socket-server
Dependencies
socket.io, jsonwebtoken
Code
import { Server, Socket } from "socket.io";
import jwt from "jsonwebtoken";
import type { Server as HTTPServer } from "http";
interface JwtPayloadOptions {
id: string;
email: string;
name: string;
}
export interface AuthenticatedSocket extends Socket {
user?: JwtPayloadOptions;
}
interface InitSocketOptions {
/** The HTTP server instance to attach socket.io to */
server: HTTPServer;
/**
* Allowed CORS origins
* @default "*"
*/
allowedOrigins?: string | string[];
/**
* Allowed HTTP methods for CORS
* @default ["GET", "POST"]
*/
allowedMethods?: string[];
/** Allowed headers for CORS */
allowedHeaders?: string[];
/**
* Whether to validate JWT token on connection handshake
* @default true
*/
validateToken?: boolean;
}
export function initializeSocket({
server,
allowedOrigins = "*",
allowedMethods = ["GET", "POST"],
allowedHeaders,
validateToken = true,
}: InitSocketOptions): Server {
const io = new Server(server, {
cors: {
origin: allowedOrigins,
methods: allowedMethods,
allowedHeaders,
credentials: true,
},
});
io.use((socket: AuthenticatedSocket, next) => {
console.log(
`[${new Date().toISOString()}] Socket connected: ${socket.id}, ` +
`IP: ${socket.handshake.address}, ` +
`Transport: ${socket.conn.transport}`
);
// If validation is disabled, skip auth check
if (!validateToken) return next();
const token = socket.handshake.query.token as string;
if (!token) return next(new Error("Authentication error"));
try {
const secret: jwt.Secret = process.env.JWT_ACCESS_SECRET!;
const decoded = jwt.verify(token, secret) as JwtPayloadOptions;
socket.user = decoded;
next();
} catch (err) {
console.error("JWT verification failed:", err);
next(new Error("Authentication error"));
}
});
return io;
}
Usage
import { createSocketServer } from './libs/servers/socket-server';
const io = createSocketServer(httpServer);
io.on('connection', (socket) => {
console.log('Client connected');
});
Dependencies
socket.iojsonwebtoken
Frequently Asked Questions
How do I install Socket.io Server?
Run the following command:
npx hanma add socket-serverWhat dependencies are required?
This snippet requires: socket.io, jsonwebtoken. Make sure to install them before using the snippet.
How do I use this snippet?
Copy the code and paste it into your project. The snippet will be saved to
libs/servers/socket-server.ts.Can I customize this snippet?
Yes! All snippets are copy-paste code that you own. Feel free to modify them to fit your needs.
Does this work with other frameworks?
This snippet is designed for the specific framework. Check the other framework pages for equivalent implementations.