Server Setup & Configuration
Set up a Mesh server with just a few lines of code.
Basic usage
import { MeshServer } from "@mesh-kit/core/server";
const server = new MeshServer({
port: 8080,
redisOptions: { host: "localhost", port: 6379 },
});
server.exposeCommand("echo", async (ctx) => {
return `echo: ${ctx.payload}`;
});
The server starts listening immediately. To be sure it’s up, you can: await server.ready()
.
Configuration options
const server = new MeshServer({
port: 8080,
host: "0.0.0.0", // default
path: "/mesh", // WebSocket path (default "/")
redisOptions: {
host: "localhost",
port: 6379,
password: "optional",
},
pingInterval: 30_000,
latencyInterval: 5_000,
maxMissedPongs: 1,
enablePresenceExpirationEvents: true,
});
redisOptions
are passed directly to ioredis . You can use any valid ioredis client option here.
Handling connections
server.onConnection(async (conn) => {
console.log("Connected:", conn.id);
await server.connectionManager.setMetadata(conn, {
connectedAt: Date.now(),
});
});
server.onDisconnection(async (conn) => {
console.log("Disconnected:", conn.id);
});
Graceful shutdown
process.on("SIGINT", async () => {
console.log("Shutting down...");
await server.close();
process.exit(0);
});
Using with Express
To integrate with an existing Express + HTTP server:
npm install @mesh-kit/express
import express from "express";
import http from "http";
import createMeshMiddleware from "@mesh-kit/express";
const app = express();
const httpServer = http.createServer(app);
const { middleware, mesh } = createMeshMiddleware(httpServer, {
path: "/ws",
redisOptions: { host: "localhost", port: 6379 },
});
app.use(middleware); // optional — for `.ws()` support
mesh.exposeCommand("echo", async (ctx) => {
return `echo: ${ctx.payload}`;
});
httpServer.listen(3000, () => {
console.log("Server listening on port 3000");
});
💡
The middleware handles WebSocket upgrades via the upgrade
event. The middleware is
optional and only needed for .ws()
support.
Next steps
Last updated on