npm install @ezez/ws-server
Here's a minimal WebSocket server with authentication and type-safe messaging:
import { EZEZWebsocketServer } from "@ezez/ws-server";
// Define what events clients can send to the server
type IncomingEvents = {
greet: [name: string];
sum: [a: number, b: number];
};
// Define what events the server can send to clients
type OutgoingEvents = {
welcome: [message: string];
result: [value: number];
};
const server = new EZEZWebsocketServer<IncomingEvents, OutgoingEvents>(
{ port: 8080 },
{
onAuthRequest: async (client, authKey) => {
// Validate the auth key sent by the client
return authKey === "my-secret-key";
},
onAuthOk: (client) => {
client.send("welcome", ["You are connected!"]);
},
onMessage: (client, eventName, args, reply, ids) => {
console.log("Received:", eventName, args);
},
},
);
await server.start();
console.log("Server listening on port 8080");
onAuthRequest callback decides whether to accept or rejectAfter authentication, you can send messages to individual clients or broadcast to all:
// Send to a specific client
client.send("welcome", ["Hello!"]);
// Broadcast to all connected clients
server.broadcast("result", [42]);
There are two ways to handle incoming messages:
client.on()Listen for specific events on individual clients:
onAuthOk: (client) => {
client.on("greet", (args, reply) => {
const [name] = args;
reply("welcome", [`Hello, ${name}!`]);
});
client.on("sum", (args, reply) => {
const [a, b] = args;
reply("result", [a + b]);
});
}
onMessage callbackReceives every message from every client:
const server = new EZEZWebsocketServer<IncomingEvents, OutgoingEvents>(
{ port: 8080 },
{
onAuthRequest: async () => true,
onMessage: (client, eventName, args, reply, ids) => {
if (eventName === "greet") {
const [name] = args;
reply("welcome", [`Hello, ${name}!`]);
}
},
},
);