building-a-real-time-web-application-using-nestjs-and-postgresql.html

Building a Real-Time Web Application Using NestJS and PostgreSQL

In today’s fast-paced digital landscape, real-time web applications are becoming increasingly essential. From collaborative tools to live notifications, the demand for systems that can handle real-time data is soaring. One powerful stack for building such applications is NestJS combined with PostgreSQL. This article will guide you through the process of creating a real-time web application using these technologies, offering clear code examples and actionable insights along the way.

What is NestJS?

NestJS is a progressive Node.js framework for building efficient and scalable server-side applications. It leverages TypeScript, making it a great choice for developers who want to write type-safe code. With its modular architecture, NestJS allows for easy management of complex applications, making it ideal for teams working on large-scale projects.

Key Features of NestJS:

  • Modular Architecture: Break down your application into reusable modules.
  • Dependency Injection: Easily manage dependencies through a powerful injection system.
  • TypeScript Support: Enhance code quality with static typing.
  • Extensive Libraries: Access a rich ecosystem of libraries and tools.

What is PostgreSQL?

PostgreSQL is a powerful, open-source relational database management system (RDBMS) that emphasizes extensibility and SQL compliance. Known for its robustness and reliability, PostgreSQL is an excellent choice for applications that require complex queries and large volumes of data.

Key Features of PostgreSQL:

  • ACID Compliance: Guarantees data integrity.
  • Advanced Queries: Supports complex queries and transactions.
  • Extensibility: Allows users to create custom data types and functions.
  • Strong Community: Benefit from a vibrant community and extensive documentation.

Use Cases for Real-Time Applications

Real-time web applications find their use in various domains, such as: - Chat Applications: Enable users to communicate instantly. - Collaborative Tools: Allow multiple users to work on the same document simultaneously. - Live Data Monitoring: Provide updates on metrics or statistics in real time. - Gaming: Facilitate multiplayer interactions without latency.

Setting Up Your Development Environment

Before diving into coding, you’ll need to set up your development environment. Ensure you have Node.js and PostgreSQL installed on your machine. You can download them from their official websites.

Step 1: Initialize Your NestJS Project

Open your terminal and run the following commands to create a new NestJS project:

npm i -g @nestjs/cli
nest new real-time-app
cd real-time-app

Step 2: Install Required Dependencies

Next, you’ll need to install the necessary packages for PostgreSQL and WebSockets.

npm install @nestjs/typeorm typeorm pg @nestjs/websockets @nestjs/platform-socket.io

Step 3: Set Up PostgreSQL Connection

Open the app.module.ts file to configure the database connection using TypeORM.

import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { Message } from './message.entity';
import { MessageModule } from './message/message.module';

@Module({
  imports: [
    TypeOrmModule.forRoot({
      type: 'postgres',
      host: 'localhost',
      port: 5432,
      username: 'your_username',
      password: 'your_password',
      database: 'your_database',
      entities: [Message],
      synchronize: true,
    }),
    MessageModule,
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

Step 4: Create a Message Entity

Create a new file called message.entity.ts in the src folder.

import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';

@Entity()
export class Message {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  content: string;
}

Step 5: Implement WebSocket Gateway

Create a new gateway to handle real-time communications. Create a file named message.gateway.ts.

import {
  WebSocketGateway,
  WebSocketServer,
  SubscribeMessage,
  OnGatewayInit,
  Socket,
} from '@nestjs/websockets';
import { Server } from 'socket.io';
import { Message } from './message.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { MessageService } from './message.service';

@WebSocketGateway()
export class MessageGateway implements OnGatewayInit {
  @WebSocketServer() server: Server;

  constructor(
    @InjectRepository(Message)
    private messageRepository: Repository<Message>,
    private messageService: MessageService,
  ) {}

  afterInit(server: Server) {
    console.log('WebSocket Initialized');
  }

  @SubscribeMessage('sendMessage')
  async handleMessage(client: Socket, payload: string): Promise<void> {
    const message = await this.messageService.createMessage(payload);
    this.server.emit('message', message);
  }
}

Step 6: Create a Message Service

To handle the message logic, create a service called message.service.ts.

import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Message } from './message.entity';

@Injectable()
export class MessageService {
  constructor(
    @InjectRepository(Message)
    private messageRepository: Repository<Message>,
  ) {}

  async createMessage(content: string): Promise<Message> {
    const message = this.messageRepository.create({ content });
    return this.messageRepository.save(message);
  }
}

Step 7: Update the Message Module

Ensure your message.module.ts imports the necessary components.

import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Message } from './message.entity';
import { MessageGateway } from './message.gateway';
import { MessageService } from './message.service';

@Module({
  imports: [TypeOrmModule.forFeature([Message])],
  providers: [MessageGateway, MessageService],
})
export class MessageModule {}

Step 8: Test Your Application

Now, you can run your NestJS application.

npm run start

Next, connect to your WebSocket server using a client like Socket.IO to test message broadcasting.

Conclusion

Building a real-time web application with NestJS and PostgreSQL is a powerful way to create engaging user experiences. By following the steps outlined in this article, you’ve set up a solid foundation for your application. As you expand your app, consider implementing features like user authentication, message history, and error handling to enhance functionality.

Key Takeaways:

  • NestJS provides a modular and scalable architecture.
  • PostgreSQL is an excellent choice for data management.
  • WebSockets enable real-time communication.

Get started now and explore the limitless possibilities of real-time applications!

SR
Syed
Rizwan

About the Author

Syed Rizwan is a Machine Learning Engineer with 5 years of experience in AI, IoT, and Industrial Automation.