Working with WebSockets in Node.js using TypeScript
November 6, 2023
WebSockets enable full-duplex communication between a server and client, making them ideal for building real-time applications. This guide will provide a step-by-step process for setting up a WebSocket server using Node.js and TypeScript.
- Basic knowledge of TypeScript and Node.js
- Node.js installed
- A package manager (like npm or yarn)
1. Setting up the Project
First, let's create a new directory for our project and initialize a new Node.js project:
Now, let's install and configure TypeScript:
This will create a
tsconfig.json file. You can adjust the compiler options based on your needs, but for this guide, the defaults should be sufficient.
2. Installing Required Packages
We'll be using the
ws library for handling WebSocket connections. To install it and its type definitions:
3. Creating the WebSocket Server
Create a new file called
4. Handling Client Connections
Extend the code in
server.ts to handle client connections, messages, and disconnections.
5. Running the Server
With everything set up, we just need to start our HTTP server. Add the following code at the end of
To run your WebSocket server, compile the TypeScript code and then start the server:
Your WebSocket server should now be running on
http://localhost:8080/. Clients can connect to it and start sending and receiving real-time messages.
How to fix the "not all code paths return a value" issue in TypeScript
Type Annotations Can Only Be Used in TypeScript Files
Guide to TypeScript Recursive Type
How to Configure Knex.js with TypeScript
"No overload matches this call" in TypeScript