Setup Socket.io Typescript

Thumbnail

Written by: developervsandhu

Technology and Gadgets

Setup Socket.io Typescript

This blog is about setting up typescript socket io server for realtime functionallity.

  • Install socket io
	npm install socket.io
  • After installing we need to declare it's type to express js
  • Create a file in /types/index.d.ts
  • Configure Typescript
	"typeRoots": ["./types", "./node_modules/types"]
  • In the index.d.ts file add the following code snippet
	import { Server as SocketIoServer} from "socket.io";
	
	declare global {
		namespace Express {
			interface Application {
				io?: SocketIoServer
			}
		}
	}
  • Then add follwing code in index.ts file
	import  http  from  "http";
	import { Server  as  SocketIOServer } from  "socket.io";
	import express from "express";
	
	const app:Express = express();
	const server = http.createServer(app);
	const io = new SocketIoServer {server, {
			cors: {
				origin: "http://localhost:5173",
				methods: ["GET", "POST", "PUT", "DELETE"],
				credentials: true,
			}
		}
	}
	app.io = io
  • After Setting up your socket server is ready to use
	// This code must be added to your routes in order to use socket io
	const socket = req.app.io;
	socket?.emit("event_name", event_name);
  • That's it you have successfully setup your socket io server and you are good to go :)

Login To Add Comment

No comments yet.