How to Create a Secure gRPC Client in NestJS with SSL/TLS
Development

How to Create a Secure gRPC Client in NestJS with SSL/TLS

By AtenTEC Engineering Team4 min read

How to Create a Secure gRPC Client in NestJS with SSL/TLS

If you’re building microservices with NestJS, chances are you’ve heard of gRPC and Protocol Buffers (protobuf). gRPC is known for its high performance, strong typing, and efficient communication between distributed systems.

But here’s the catch: while there are plenty of tutorials on gRPC in Node.js, there are fewer guides that explain how to set up a secure gRPC client in NestJS with SSL/TLS enabled. That’s exactly what this tutorial will cover.

By the end of this guide, you’ll know how to:

  • Create a NestJS gRPC client.
  • Configure it to use SSL/TLS encryption.
  • Consume a secure gRPC endpoint with protobuf definitions.

Why Use gRPC with SSL in NestJS?

When building microservices, security is as important as performance. Enabling SSL/TLS ensures that communication between services is encrypted and secure from interception.

Using gRPC with SSL in NestJS gives you:

  • Secure communication between services.
  • High performance with Protocol Buffers.
  • Strongly typed contracts for safer development.

Step 1: Create a New NestJS Project

Let’s start fresh with a new NestJS project using the CLI:

nest new [project_name]

Step 2: Install gRPC Dependencies

Next, install the packages required to work with gRPC in NestJS:

npm i --save @grpc/grpc-js @grpc/proto-loader @nestjs/microservices

Step 3: Generate a Module and Controller

For this example, we’ll create a simple Hero module and controller:

nest g module hero
nest g controller hero

Step 4: Define the gRPC Service Using a .proto File

Inside the hero folder, create a hero.proto file. This defines the protobuf service contract that both the client and server will use.

syntax = "proto3";
 
package hero;
 
service HeroesService {
  rpc FindOne (HeroById) returns (Hero) {}
}
 
message HeroById {
  int32 id = 1;
}
 
message Hero {
  int32 id = 1;
  string name = 2;
}

This service exposes a simple FindOne method to retrieve a hero by ID.


Step 5: Configure the Secure gRPC Client in the Module

Now, let’s configure the gRPC client inside HeroModule. The key part here is enabling SSL credentials.

import { Module } from "@nestjs/common";
import {
  ClientProxyFactory,
  Transport,
  ClientGrpc,
} from "@nestjs/microservices";
import { join } from "path";
import { ChannelCredentials } from "@grpc/grpc-js";
import { HeroController } from "./hero.controller";
 
@Module({
  controllers: [HeroController],
  providers: [
    {
      provide: "HERO_SERVICE",
      useFactory: () => {
        return ClientProxyFactory.create({
          transport: Transport.GRPC,
          options: {
            package: "hero",
            protoPath: join(process.cwd(), "src/hero/hero.proto"),
            url: "[your-secure-server-domain:port]",
            credentials: ChannelCredentials.createSsl(), // ✅ SSL/TLS enabled
          },
        });
      },
    },
  ],
})
export class HeroModule {}

Step 6: Implement the Hero Controller

Next, wire the gRPC client inside the HeroController. This is where we call the secure gRPC service.

import { Controller, Inject, OnModuleInit } from "@nestjs/common";
import { ClientGrpc } from "@nestjs/microservices";
import { Observable } from "rxjs";
import { Metadata } from "@grpc/grpc-js";
 
interface HeroesService {
  findOne(data: { id: number }, metadata?: Metadata): Observable<any>;
}
 
@Controller("hero")
export class HeroController implements OnModuleInit {
  private heroesService: HeroesService;
 
  constructor(@Inject("HERO_SERVICE") private client: ClientGrpc) {}
 
  onModuleInit() {
    this.heroesService = this.client.getService<HeroesService>("HeroesService");
  }
 
  getHero(): Observable<any> {
    const metadata = new Metadata();
    metadata.add("Set-Cookie", "yummy_cookie=choco"); // optional metadata
 
    return this.heroesService.findOne({ id: 1 }, metadata);
  }
}

Step 7: Run the NestJS Application

Finally, start your NestJS app:

npm run start:dev

Now, open your browser and go to:

http://[host:port]/hero

You should see the response from your secure gRPC server over SSL.


Wrapping Up

You’ve now built a NestJS gRPC client with SSL/TLS enabled. This setup allows your services to communicate securely and efficiently — a key requirement for any production-grade microservices architecture.

Here’s what we achieved:

  • Defined a gRPC service using .proto files.
  • Configured a secure gRPC client in NestJS.
  • Successfully consumed a gRPC endpoint with SSL.

In real-world projects, you can take this further by:

  • Using mutual TLS (mTLS) with client certificates.
  • Expanding .proto files for more complex services.
  • Integrating your gRPC client into larger NestJS microservice ecosystems.

Key Takeaways

  • NestJS + gRPC is a powerful combo for building scalable microservices.
  • SSL/TLS encryption is essential for securing service-to-service communication.
  • With the right setup, you can leverage the speed and reliability of protobuf while keeping data safe.

If you’re searching for a practical NestJS gRPC tutorial that includes secure client setup with SSL/TLS, this guide has you covered.

Category

Development

Tags

NestJS
gRPC
SSL
Microservices
Protobuf
AtenTEC Engineering Team

AtenTEC Engineering Team

The AtenTEC engineering team shares tutorials, insights, and best practices for building innovative, secure, and scalable software solutions.

Related Articles

Mastering Modern Authentication: A Guide to Secure Communication
5 min read

Mastering Modern Authentication: A Guide to Secure Communication

This article provides a practical guide to modern authentication patterns using OIDC and OAuth 2.0. Through three easy-to-understand sequence diagrams, it visualizes the secure flows for backend-to-backend communication, frontend-to-backend user logins with stateful sessions, and a combined scenario where a backend service makes a B2B call to fulfill a frontend request. It explains the core concepts of token exchange, session management, and role-based access control (RBAC), making these complex interactions accessible to developers and system architects.

How does Microservices Architecture in Aten FleetFix Enhance Workshop Operations?
4 min read

How does Microservices Architecture in Aten FleetFix Enhance Workshop Operations?

This article explains how Aten FleetFix’s Microservices architecture transforms mid-to-large auto repair workshops by breaking down operations into modular, independent services. Unlike traditional monolithic ERPs that create bottlenecks and scaling issues, FleetFix enables faster repair order processing, smarter inventory management, scalable growth, and enhanced customer experiences. The result is a 40% faster repair cycle, 30% lower stock waste, and significantly higher customer satisfaction, making microservices the future of auto repair management.

Optimizing Multi-Branch Auto Repair Operations
2 min read

Optimizing Multi-Branch Auto Repair Operations

A leading Gulf-based car rental company struggled with operational inefficiencies in its multi-branch auto repair workshops due to disorganized workflows, poor spare parts management, and high costs. By implementing Aten FleetFix, the company centralized repair order management, automated spare parts tracking, and introduced data-driven cost optimization. Within six months, they achieved 30% faster repair cycles, 25% shorter spare parts procurement time, 15% lower costs, and 20% higher overall efficiency, transforming their fragmented operations into a streamlined, cost-effective network.

Background

Stay in the loop

Need to know more? book a consultation meeting now