This is a great request for a comprehensive NestJS boilerplate. The user wants:
A NestJS application with hybrid support (HTTP + Microservices)
HTTP REST API on port 3000
gRPC server on port 5000
Shared service layer between both transports
I'll need to create a complete, production-ready boilerplate that includes:
Project structure
Main bootstrap file (main.ts)
App module
Controllers for REST
gRPC handler/controller
Shared service
Proto files for gRPC
Package.json with dependencies
Configuration files
DTOs
Guards, interceptors, etc.
Let me create a comprehensive solution with multiple files:
main.ts - Hybrid application setup
app.module.ts - Root module
proto file - gRPC service definition
service - Shared business logic
rest controller
gRPC handler
DTOs
.env.example
package.json
tsconfig.json
.eslintrc.js (optional)
.prettierrc (optional)
Let me organize this properly with detailed comments and examples.
NestJS Hybrid Application Boilerplate (HTTP + gRPC)
I'll provide a complete, production-ready boilerplate with REST and gRPC support sharing a common service layer.
Project Structure
code Copy code
src/
├── common/
│ ├── decorators/
│ ├── guards/
│ ├── interceptors/
│ └── filters/
├── config/
│ └── configuration.ts
├── grpc/
│ ├── handlers/
│ │ └── user.handler.ts
│ └── user-grpc.service.ts
├── proto/
│ └── user.proto
├── shared/
│ ├── dto/
│ │ └── user.dto.ts
│ └── services/
│ └── user.service.ts
├── rest/
│ ├── controllers/
│ │ └── user.controller.ts
│ └── user-rest.service.ts
├── app.module.ts
└── main.ts
1. Proto File
protobuf Copy code
// src/proto/user.proto
syntax = "proto3";
package user;
service UserService {
rpc GetUser (GetUserRequest) returns (UserResponse);
rpc CreateUser (CreateUserRequest) returns (UserResponse);
rpc UpdateUser (UpdateUserRequest) returns (UserResponse);
rpc DeleteUser (DeleteUserRequest) returns (DeleteUserResponse);
rpc ListUsers (ListUsersRequest) returns (ListUsersResponse);
}
message GetUserRequest {
int32 id = 1;
}
message CreateUserRequest {
string name = 1;
string email = 2;
int32 age = 3;
}
message UpdateUserRequest {
int32 id = 1;
string name = 2;
string email = 3;
int32 age = 4;
}
message DeleteUserRequest {
int32 id = 1;
}
message UserResponse {
int32 id = 1;
string name = 2;
string email = 3;
int32 age = 4;
string createdAt = 5;
}
message DeleteUserResponse {
bool success = 1;
string message = 2;
}
message ListUsersRequest {
int32 page = 1;
int32 limit = 2;
}
message ListUsersResponse {
repeated UserResponse users = 1;
int32 total = 2;
int32 page = 3;
}
2. DTOs (Shared)
typescript Copy code
// src/shared/dto/user.dto.ts
import { IsEmail, IsInt, IsString, Min, Max, IsOptional } from 'class-validator';
export class CreateUserDto {
@IsString()
name: string;
@IsEmail()
email: string;
@IsInt()
@Min(1)
@Max(150)
age: number;
}
export class UpdateUserDto {
@IsOptional()
@IsString()
name?: string;
@IsOptional()
@IsEmail()
email?: string;
@IsOptional()
@IsInt()
@Min(1)
@Max(150)
age?: number;
}
export class UserResponseDto {
id: number;
name: string;
email: string;
age: number;
createdAt: Date;
}
3. Shared Service (Business Logic)
typescript Copy code
// src/shared/services/user.service.ts
import { Injectable, NotFoundException, BadRequestException } from '@nestjs/common';
import { CreateUserDto, UpdateUserDto, UserResponseDto } from '../dto/user.dto';
interface User {
id: number;
name: string;
email: string;
age: number;
createdAt: Date;
}
@Injectable()
export class UserService {
private users: User[] = [
{
id: 1,
name: 'John Doe',
email: 'john@example.com',
age: 30,
createdAt: new Date('2023-01-01'),
},
{
id: 2,
name: 'Jane Smith',
email: 'jane@example.com',
age: 28,
createdAt: new Date('2023-01-02'),
},
];
private idCounter = 3;
/**
* Get a single user by ID
*/
async getUser(id: number): Promise<UserResponseDto> {
const user = this.users.find((u) => u.id === id);
if (!user) {
throw new NotFoundException(`User with ID ${id} not found`);
}
return this.mapToDto(user);
}
/**
* Create a new user
*/
async createUser(createUserDto: CreateUserDto): Promise<UserResponseDto> {
const emailExists = this.users.some((u) => u.email === createUserDto.email);
if (emailExists) {
throw new BadRequestException(`Email ${createUserDto.email} already exists`);
}
const newUser: User = {
id: this.idCounter++,
...createUserDto,
createdAt: new Date(),
};
this.users.push(newUser);
return this.mapToDto(newUser);
}
/**
* Update an existing user
*/
async updateUser(
id: number,
updateUserDto: UpdateUserDto,
): Promise<UserResponseDto> {
const user = this.users.find((u) => u.id === id);
if (!user) {
throw new NotFoundException(`User with ID ${id} not found`);
}
// Check if new email is unique
if (
updateUserDto.email &&
updateUserDto.email !== user.email &&
this.users.some((u) => u.email === updateUserDto.email)
) {
throw new BadRequestException(`Email ${updateUserDto.email} already exists`);
}
Object.assign(user, updateUserDto);
return this.mapToDto(user);
}
/**
* Delete a user
*/
async deleteUser(id: number): Promise<boolean> {
const index = this.users.findIndex((u) => u.id === id);
if (index === -1) {
throw new NotFoundException(`User with ID ${id} not found`);
}
this.users.splice(index, 1);
return true;
}
/**
* List all users with pagination
*/
async listUsers(page: number = 1, limit: number = 10) {
const skip = (page - 1) * limit;
const paginatedUsers = this.users.slice(skip, skip + limit);
return {
users: paginatedUsers.map((u) => this.mapToDto(u)),
total: this.users.length,
page,
limit,
};
}
/**
* Map internal User to DTO
*/
private mapToDto(user: User): UserResponseDto {
return {
id: user.id,
name: user.name,
email: user.email,
age: user.age,
createdAt: user.createdAt,
};
}
}
4. REST Controller
typescript Copy code
// src/rest/controllers/user.controller.ts
import {
Controller,
Get,
Post,
Put,
Delete,
Body,
Param,
Query,
HttpCode,
HttpStatus,
UseInterceptors,
UseFilters,
} from '@nestjs/common';
import { UserService } from '../../shared/services/user.service';
import { CreateUserDto, UpdateUserDto } from '../../shared/dto/user.dto';
import { TransformInterceptor } from '../../common/interceptors/transform.interceptor';
import { HttpExceptionFilter } from '../../common/filters/http-exception.filter';
@Controller('api/users')
@UseInterceptors(TransformInterceptor)
@UseFilters(HttpExceptionFilter)
export class UserController {
constructor(private readonly userService: UserService) {}
@Get(':id')
async getUser(@Param('id') id: string) {
return this.userService.getUser(parseInt(id, 10));
}
@Post()
@HttpCode(HttpStatus.CREATED)
async createUser(@Body() createUserDto: CreateUserDto) {
return this.userService.createUser(createUserDto);
}
@Put(':id')
async updateUser(
@Param('id') id: string,
@Body() updateUserDto: UpdateUserDto,
) {
return this.userService.updateUser(parseInt(id, 10), updateUserDto);
}
@Delete(':id')
@HttpCode(HttpStatus.NO_CONTENT)
async deleteUser(@Param('id') id: string) {
await this.userService.deleteUser(parseInt(id, 10));
}
@Get()
async listUsers(
@Query('page') page: string = '1',
@Query('limit') limit: string = '10',
) {
return this.userService.listUsers(parseInt(page, 10), parseInt(limit, 10));
}
@Get('health/check')
healthCheck() {
return { status: 'ok', timestamp: new Date() };
}
}
5. gRPC Handler
typescript Copy code
// src/grpc/handlers/user.handler.ts
import { Controller } from '@nestjs/common';
import { GrpcMethod, GrpcStreamMethod } from '@nestjs/microservices';
import { UserService } from '../../shared/services/user.service';
import { CreateUserDto, UpdateUserDto } from '../../shared/dto/user.dto';
import { Observable } from 'rxjs';
@Controller()
export class UserGrpcHandler {
constructor(private readonly userService: UserService) {}
@GrpcMethod('UserService', 'GetUser')
async getUser(request: { id: number }) {
const user = await this.userService.getUser(request.id);
return this.mapToGrpcResponse(user);
}
@GrpcMethod('UserService', 'CreateUser')
async createUser(request: any) {
const createUserDto: CreateUserDto = {
name: request.name,
email: request.email,
age: request.age,
};
const user = await this.userService.createUser(createUserDto);
return this.mapToGrpcResponse(user);
}
@GrpcMethod('UserService', 'UpdateUser')
async updateUser(request: any) {
const updateUserDto: UpdateUserDto = {
name: request.name,
email: request.email,
age: request.age,
};
const user = await this.userService.updateUser(request.id, updateUserDto);
return this.mapToGrpcResponse(user);
}
@GrpcMethod('UserService', 'DeleteUser')
async deleteUser(request: { id: number }) {
await this.userService.deleteUser(request.id);
return {
success: true,
message: `User ${request.id} deleted successfully`,
};
}
@GrpcMethod('UserService', 'ListUsers')
async listUsers(request: { page: number; limit: number }) {
const result = await this.userService.listUsers(
request.page || 1,
request.limit || 10,
);
return {
users: result.users.map((u) => this.mapToGrpcResponse(u)),
total: result.total,
page: result.page,
};
}
private mapToGrpcResponse(user: any) {
return {
id: user.id,
name: user.name,
email: user.email,
age: user.age,
createdAt: user.createdAt.toISOString(),
};
}
}
6. Common Interceptors
typescript Copy code
// src/common/interceptors/transform.interceptor.ts
import {
Injectable,
NestInterceptor,
ExecutionContext,
CallHandler,
} from '@nestjs/common';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
@Injectable()
export class TransformInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
return next.handle().pipe(
map((data) => ({
success: true,
timestamp: new Date().toISOString(),
data: data || null,
})),
);
}
}
typescript Copy code
// src/common/filters/http-exception.filter.ts
import {
ExceptionFilter,
Catch,
ArgumentsHost,
HttpException,
HttpStatus,
Logger,
} from '@nestjs/common';
import { Request, Response } from 'express';
@Catch()
export class HttpExceptionFilter implements ExceptionFilter {
private readonly logger = new Logger(HttpExceptionFilter.name);
catch(exception: unknown, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const response = ctx.getResponse<Response>();
const request = ctx.getRequest<Request>();
let status = HttpStatus.INTERNAL_SERVER_ERROR;
let message = 'Internal server error';
if (exception instanceof HttpException) {
status = exception.getStatus();
const exceptionResponse = exception.getResponse();
message =
(exceptionResponse as any).message || exception.message;
} else if (exception instanceof Error) {
message = exception.message;
}
this.logger.error(
`[${request.method}] ${request.url} - ${status} - ${message}`,
exception instanceof Error ? exception.stack : '',
);
response.status(status).json({
success: false,
timestamp: new Date().toISOString(),
path: request.url,
message,
});
}
}
7. Configuration
typescript Copy code
// src/config/configuration.ts
export interface IConfig {
http: {
port: number;
};
grpc: {
port: number;
protoPath: string;
};
}
export const configuration = (): IConfig => ({
http: {
port: parseInt(process.env.HTTP_PORT || '3000', 10),
},
grpc: {
port: parseInt(process.env.GRPC_PORT || '5000', 10),
protoPath: process.env.PROTO_PATH || './proto/user.proto',
},
});
8. App Module
typescript Copy code
// src/app.module.ts
import { Module } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { ClientsModule, Transport } from '@nestjs/microservices';
import { join } from 'path';
import { configuration } from './config/configuration';
import { UserService } from './shared/services/user.service';
import { UserController } from './rest/controllers/user.controller.ts';
import { UserGrpcHandler } from './grpc/handlers/user.handler';
@Module({
imports: [
ConfigModule.forRoot({
load: [configuration],
isGlobal: true,
}),
],
controllers: [UserController, UserGrpcHandler],
providers: [UserService],
})
export class AppModule {}
9. Main Bootstrap File
typescript Copy code
// src/main.ts
import { NestFactory } from '@nestjs/core';
import { MicroserviceOptions, Transport } from '@nestjs/microservices';
import { ConfigService } from '@nestjs/config';
import { ValidationPipe, Logger } from '@nestjs/common';
import { join } from 'path';
import { AppModule } from './app.module';
const logger = new Logger('Bootstrap');
async function bootstrap() {
// Create HTTP application
const app = await NestFactory.create(AppModule);
const configService = app.get(ConfigService);
// Validation pipe
app.useGlobalPipes(
new ValidationPipe({
whitelist: true,
forbidNonWhitelisted: true,
transform: true,
transformOptions: {
enableImplicitConversion: true,
},
}),
);
// Enable CORS
app.enableCors({
origin: process.env.CORS_ORIGIN || '*',
credentials: true,
});
const httpPort = configService.get<number>('http.port', 3000);
const grpcPort = configService.get<number>('grpc.port', 5000);
// Start HTTP server
await app.listen(httpPort, () => {
logger.log(`🚀 HTTP REST API is running on port ${httpPort}`);
logger.log(`📚 Swagger docs available at http://localhost:${httpPort}/api`);
});
// Connect microservice (gRPC)
const grpcUrl = `0.0.0.0:${grpcPort}`;
app.connectMicroservice<MicroserviceOptions>(
{
transport: Transport.GRPC,
options: {
url: grpcUrl,
package: 'user',
protoPath: join(__dirname, '../src/proto/user.proto'),
onLoadPackageDefinition: (pkg, server) => {
logger.log(`✅ gRPC package loaded: user`);
},
},
},
{ inheritAppConfig: false },
);
// Start all microservices
await app.startAllMicroservices();
logger.log(`🔗 gRPC Server is running on port ${grpcPort}`);
logger.log(`📦 Available at ${grpcUrl}`);
logger.log(`
╔════════════════════════════════════════════╗
║ NestJS Hybrid Application Started ║
╠════════════════════════════════════════════╣
║ HTTP REST: http://localhost:${httpPort} ║
║ gRPC: ${grpcUrl} ║
╚════════════════════════════════════════════╝
`);
}
bootstrap().catch((error) => {
logger.error('Error during bootstrap', error);
process.exit(1);
});
10. Package.json
json Copy code
{
"name": "nestjs-hybrid-app",
"version": "1.0.0",
"description": "NestJS Hybrid Application with HTTP and gRPC",
"author": "Your Name",
"private": true,
"license": "MIT",
"scripts": {
"prebuild": "rimraf dist",
"build": "nest build",
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
"start": "nest start",
"start:dev": "nest start --watch",
"start:debug": "nest start --debug --watch",
"start:prod": "node dist/main",
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
"test": "jest",
"test:watch": "jest --watch",
"test:cov": "jest --coverage",
"test:e2e": "jest --config ./test/jest-e2e.json"
},
"dependencies": {
"@nestjs/common": "^10.2.10",
"@nestjs/config": "^3.1.1",
"@nestjs/core": "^10.2.10",
"@nestjs/microservices": "^10.2.10",
"@nestjs/platform-express": "^10.2.10",
"class-transformer": "^0.5.1",
"class-validator": "^0.14.0",
"reflect-metadata": "^0.1.13",
"rimraf": "^5.0.5",
"rxjs": "^7.8.1"
},
"devDependencies": {
"@nestjs/cli": "^10.2.1",
"@nestjs/schematics": "^10.0.3",
"@types/express": "^4.17.21",
"@types/jest": "^29.5.8",
"@types/node": "^20.10.5",
"@typescript-eslint/eslint-plugin": "^6.15.0",
"@typescript-eslint/parser": "^6.15.0",
"eslint": "^8.56.0",
"jest": "^29.7.0",
"prettier": "^3.1.1",
"ts-jest": "^29.1.1",
"ts-loader": "^9.5.1",
"ts-node": "^10.9.2",
"typescript": "^5.3.3"
}
}
11. TypeScript Config
json Copy code
{
"compilerOptions": {
"module": "commonjs",
"declaration": true,
"removeComments": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"allowSyntheticDefaultImports": true,
"target": "ES2021",
"sourceMap": true,
"outDir": "./dist",
"baseUrl": "./",
"incremental": true,
"skipLibCheck": true,
"strictNullChecks": false,
"strictFunctionTypes": false,
"strictBindCallApply": false,
"strictPropertyInitialization": false,
"noImplicitAny": false,
"alwaysStrict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
"resolveJsonModule": true,
"esModuleInterop": true,
"moduleResolution": "node"
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist", "test", "**/*spec.ts"]
}
12. Environment File
bash Copy code
# .env.example
NODE_ENV=development
HTTP_PORT=3000
GRPC_PORT=5000
CORS_ORIGIN=*
PROTO_PATH=./proto/user.proto
13. Testing the Application
REST API Examples
bash Copy code
# Get user
curl http://localhost:3000/api/users/1
# Create user
curl -X POST http://localhost:3000/api/users \
-H "Content-Type: application/json" \
-d '{
"name": "Alice Johnson",
"email": "alice@example.com",
"age": 32
}'
# Update user
curl -X PUT http://localhost:3000/api/users/1 \
-H "Content-Type: application/json" \
-d '{
"name": "Alice Johnson Updated",
"age": 33
}'
# List users
curl http://localhost:3000/api/users?page=1&limit=10
# Delete user
curl -X DELETE http://localhost:3000/api/users/1
gRPC Testing with grpcurl
bash Copy code
# Install grpcurl (macOS)
brew install grpcurl
# Get user
grpcurl -plaintext -d '{"id": 1}' \
localhost:5000 user.UserService/GetUser
# Create user
grpcurl -plaintext -d '{
"name": "Bob Smith",
"email": "bob@example.com",
"age": 35
}' localhost:5000 user.UserService/CreateUser
# List users
grpcurl -plaintext -d '{"page": 1, "limit": 10}' \
localhost:5000 user.UserService/ListUsers
# Delete user
grpcurl -plaintext -d '{"id": 1}' \
localhost:5000 user.UserService/DeleteUser
14. Docker Support
dockerfile Copy code
# Dockerfile
FROM node:18-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY dist ./dist
COPY src/proto ./src/proto
EXPOSE 3000 5000
CMD ["node", "dist/main"]
yaml Copy code
# docker-compose.yml
version: '3.8'
services:
nestjs-app:
build: .
ports:
- "3000:3000"
- "5000:5000"
environment:
NODE_ENV: production
HTTP_PORT: 3000
GRPC_PORT: 5000
volumes:
- ./src/proto:/app/src/proto
15. Running the Application
bash Copy code
# Install dependencies
npm install
# Start in development mode
npm run start:dev
# Build for production
npm build
# Run production build
npm run start:prod
# Using Docker
docker-compose up --build
Key Features
✅ Hybrid Architecture - Simultaneously responds to HTTP and gRPC
✅ Shared Services - Single business logic layer for both transports
✅ Type Safety - Full TypeScript support
✅ Validation - Class-validator integrated
✅ Error Handling - Comprehensive exception filters
✅ Configuration - Environment-based configuration
✅ Proto Definitions - Strongly typed gRPC contracts
✅ Scalable - Service-oriented architecture
✅ Production Ready - Includes Docker support
This boilerplate provides a solid foundation for building microservices with both REST and gRPC interfaces!