DEV Community

Cover image for ⚡ Setting Up the Server for a Real-Time Chat App with TypeScript & Express
HILQIA KENDA
HILQIA KENDA

Posted on • Originally published at linkedin.com

⚡ Setting Up the Server for a Real-Time Chat App with TypeScript & Express

Real-time applications are everywhere today — from chat apps to trading dashboards. I recently started working on a real-time chat application, and the first step was setting up the server to handle secure, scalable communication.

Here’s a walkthrough of the setup:

🏗️ Project Structure

I’m building the app in TypeScript with Express.
The backend structure looks like this:

backend/  
 └── src/  
     ├── features/  
     ├── shared/  
     ├── config.ts  
     ├── routes.ts  
     ├── setupDatabase.ts  
     └── setupServer.ts  
Enter fullscreen mode Exit fullscreen mode

⚙️ The Server Setup(setupServer.ts)

Here’s the core of the server class:

import {
  Application,
  json,
  urlencoded,
  Response,
  Request,
  NextFunction,
} from 'express';
import http from 'http';
import cors from 'cors';
import hpp from 'hpp';
import cookieSession from 'cookie-session';
import HTTP_STATUS from 'http-status-codes';
import 'express-async-errors';
import helmet from 'helmet';
import compression from 'compression';

export class ChattyServer {
  private app: Application;

  constructor(app: Application) {
    this.app = app;
  }

  public start(): void {
    this.securityMiddleware(this.app);
    this.standardMiddleware(this.app);
    this.routeMiddleware(this.app);
    this.globalErrorHandler(this.app);
    this.startServer(this.app);
  }

  private securityMiddleware(app: Application): void {
    app.use(cookieSession({
      name: 'session',
      keys: ['key1', 'key2'],
      maxAge: 24 * 60 * 60 * 1000
    }));
    app.use(hpp());
    app.use(helmet());
    app.use(cors());
  }
}

Enter fullscreen mode Exit fullscreen mode

🔐 Security Middleware

Real-time apps need robust security because of constant data exchange. I’ve added:

  • cookie-session → lightweight session handling
  • hpp → protects against HTTP parameter pollution
  • helmet → adds secure HTTP headers
  • cors → enables cross-origin requests safely

📡 Next Steps

With the foundation in place, the next steps are:

  • Integrating a database (setupDatabase.ts)
  • Adding WebSocket support for real-time messaging
  • Implementing user authentication & chat channels

🚀 Takeaway

Setting up a server for a real-time chat app is more than just “getting Express running.” It’s about:

  • Structuring middleware for scalability
  • Prioritizing security early
  • Preparing for real-time event-driven communication

I’ll share progress on WebSocket integration in the next part. Stay tuned!

Top comments (0)