WebSocket development with Typescript from scratch

Dhruv Saksena
2 min readMay 22, 2022

--

In this article, Iam going to show how can we build a WebSocket based application in TypeScript.

We are going to create a folder in this case called websocket-example and add the below content to package.json file

{
"name": "websocket-example",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts":
{
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies":
{
"express": "^4.17.3",
"ws": "^8.5.0"
},
"devDependencies":
{
"@types/express": "^4.17.13",
"@types/ws": "^8.5.3",
"typescript": "^4.6.3"
}
}

Since, it’s TypeScript then we need to add a tsconfig.json file aswell-

{
"compilerOptions":
{
"module": "commonjs",
"strict": true,
"esModuleInterop": true,
"target": "es6",
"moduleResolution": "node",
"sourceMap": true,
"outDir": "dist",
"baseUrl": ".",
"skipLibCheck": true,
"experimentalDecorators": true,
"allowJs": true, // source code can contains ts and js files
"noImplicitAny": true, // checks all declared function arguments, they should all have types or at least any as a type.
"lib": ["es2015","es2020"],
"paths":
{
"*": ["node_modules/*"]
}
},
"include":
["src/**/*",// "test/**/*" // temprary code]
}

Finally, this is the code which is going to spawn a websocket connection on client request

import express from 'express';
import * as http from 'http';
import * as WebSocket from 'ws';
const app = express();
const server = http.createServer(app);
const webSocketServer = new WebSocket.Server({server});
webSocketServer.on('connection',
(webSocket: WebSocket)=>{
webSocket.on('message', (message: string) =>
{
console.log("Message from client :: "+ message);
webSocket.send("Echo :: " + message);
});webSocket.send("Welcome to chat !!");});server.listen(process.env.PORT || 8080, () =>{
console.log('Server started');
});

To compile the typescript program, run “tsc” on the root location.

This will produce an server.js file in the dist folder

To run the application, just type the following command, in dist folder

node server.js
Folder structure of the application

Now, I will be using WebSocket Test Client Chrome plugin to send request to server and see if this can make up a persistent socket connection-

As, you can see above the echo is working perfectly fine-

--

--