Skip to content

ledinhhuy1811/nodejs-boilerplate

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

5 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Node.js Boilerplates

A production-ready Node.js backend boilerplate built with Express, TypeScript, Prisma, and Cosmos SDK integration. This boilerplate provides a solid foundation for building scalable REST APIs with database management, authentication, logging, and blockchain integration.

πŸš€ Features

  • Express.js - Fast, unopinionated web framework
  • TypeScript - Type-safe development
  • Prisma - Modern ORM with PostgreSQL support
  • Cosmos SDK Integration - Built-in support for Oraichain blockchain interactions
  • Swagger/OpenAPI - Interactive API documentation
  • Winston Logging - Structured logging with daily rotation
  • Discord Integration - Webhook notifications for alerts and monitoring
  • Authentication - API key-based authentication middleware
  • Error Handling - Centralized error handling with custom exceptions
  • Retry Logic - Built-in retry utility for resilient operations
  • Security - Helmet, CORS, compression, and cookie parsing
  • Docker Support - PostgreSQL database containerization
  • Environment Validation - Joi-based environment variable validation

πŸ“‹ Prerequisites

  • Node.js (v18 or higher)
  • Yarn (v1.22 or higher) or npm
  • Docker and Docker Compose (for local database)
  • PostgreSQL (or use Docker Compose)

πŸ› οΈ Tech Stack

Core

  • Express ^5.2.1 - Web framework
  • TypeScript ^5.9.3 - Type safety
  • Prisma ^7.2.0 - Database ORM
  • PostgreSQL - Database

Blockchain

  • @cosmjs/cosmwasm-stargate ^0.38.1 - Cosmos SDK client
  • @cosmjs/proto-signing ^0.38.1 - Transaction signing
  • @cosmjs/amino ^0.38.1 - Amino encoding

Utilities

  • Winston ^3.19.0 - Logging
  • Winston Daily Rotate File ^5.0.0 - Log rotation
  • Swagger UI Express ^5.0.1 - API documentation
  • Discord.js ^14.25.1 - Discord webhook notifications
  • Joi ^18.0.2 - Validation
  • Helmet ^8.1.0 - Security headers
  • Morgan ^1.10.1 - HTTP request logger

πŸ“ Project Structure

nodejs-boilerplate/
β”œβ”€β”€ generated/              # Generated Prisma client
β”‚   └── prisma/
β”œβ”€β”€ logs/                   # Application logs
β”œβ”€β”€ prisma/                 # Prisma schema and migrations
β”‚   β”œβ”€β”€ migrations/
β”‚   └── models/
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ app/
β”‚   β”‚   β”œβ”€β”€ controllers/    # Route controllers
β”‚   β”‚   β”œβ”€β”€ middlewares/    # Express middlewares
β”‚   β”‚   β”œβ”€β”€ services/       # Business logic
β”‚   β”‚   └── types/          # TypeScript types
β”‚   β”œβ”€β”€ configs/            # Configuration files
β”‚   β”‚   β”œβ”€β”€ env.ts          # Environment variables
β”‚   β”‚   β”œβ”€β”€ logger.ts       # Winston logger config
β”‚   β”‚   β”œβ”€β”€ morgan.ts       # HTTP logger config
β”‚   β”‚   β”œβ”€β”€ network.ts      # Blockchain network config
β”‚   β”‚   └── swagger.ts      # Swagger/OpenAPI config
β”‚   β”œβ”€β”€ database/
β”‚   β”‚   └── docker-compose.yml  # PostgreSQL Docker setup
β”‚   β”œβ”€β”€ routes/             # Express routes
β”‚   β”œβ”€β”€ services/           # External services
β”‚   β”‚   β”œβ”€β”€ cosmosClient.ts # Cosmos SDK client
β”‚   β”‚   β”œβ”€β”€ discord.ts      # Discord webhook client
β”‚   β”‚   └── prisma.ts       # Prisma client
β”‚   β”œβ”€β”€ swaggers/           # OpenAPI YAML definitions
β”‚   β”œβ”€β”€ utils/              # Utility functions
β”‚   β”‚   β”œβ”€β”€ crypto.ts       # Encryption/decryption
β”‚   β”‚   β”œβ”€β”€ error.ts        # Error handler
β”‚   β”‚   β”œβ”€β”€ exception.ts    # Custom exceptions
β”‚   β”‚   β”œβ”€β”€ retry.ts        # Retry logic
β”‚   β”‚   β”œβ”€β”€ system.ts       # System utilities
β”‚   β”‚   └── tryCatchAsync.ts # Async error wrapper
β”‚   └── index.ts            # Application entry point
β”œβ”€β”€ package.json
β”œβ”€β”€ tsconfig.json
└── prisma.config.ts

πŸ”§ Installation

  1. Clone the repository

    git clone [email protected]:ledinhhuy1811/nodejs-boilerplate.git
    cd nodejs-boilerplate
  2. Install dependencies

    yarn install
    # or
    npm install
  3. Set up environment variables Create a .env file in the root directory:

    # Environment
    NODE_ENV=development
    PORT=8000
    
    # Database
    DATABASE_URL=postgresql://admin:root@localhost:5432/nodejs_boilerplate_db
    
    # Blockchain (Oraichain)
    ORAI_RPC_URL=http://rpc.orai.io
    
    # Security
    ENCRYPTED_MNEMONIC=your_encrypted_mnemonic_here
    PASSWORD=your_decryption_password_here
    API_KEY=your_api_key_here
    
    # Discord
    DISCORD_WEBHOOK_URL=https://discord.com/api/webhooks/your_webhook_url
  4. Start the database

    yarn db:start
  5. Run database migrations

    yarn db:migrate
  6. Generate Prisma client

    yarn db:generate

βš™οΈ Configuration

Environment Variables

Variable Description Required Default
NODE_ENV Environment (production/development/test) Yes -
PORT Server port No 8000
DATABASE_URL PostgreSQL connection string Yes -
ORAI_RPC_URL Oraichain RPC endpoint No http://rpc.orai.io
ENCRYPTED_MNEMONIC Encrypted blockchain mnemonic Yes -
PASSWORD Password for mnemonic decryption Yes -
API_KEY API key for authentication Yes -
DISCORD_WEBHOOK_URL Discord webhook URL for notifications Yes -

Encrypting Mnemonic

Use the crypto utility to encrypt your mnemonic:

import { encrypt } from "./src/utils/crypto";

const encrypted = encrypt("your-password", "your-mnemonic-phrase");
console.log(encrypted); // Use this in ENCRYPTED_MNEMONIC

πŸš€ Running the Application

Development Mode

yarn start:dev
# or
npm run start:dev

Production Mode

yarn build
yarn start
# or
npm run build
npm start

Health Check

Once the server is running, check the health endpoint:

curl http://localhost:8000/health

πŸ“š API Documentation

Swagger UI is available at:

http://localhost:8000/v1/docs/api

The API documentation is defined in YAML files under src/swaggers/ and automatically merged with the Swagger configuration.

πŸ—„οΈ Database Management

Start Database

yarn db:start

Stop Database

yarn db:stop

Create Migration

yarn db:migrate

Deploy Migrations (Production)

yarn db:deploy

Generate Prisma Client

yarn db:generate

πŸ“ Available Scripts

Script Description
yarn start Start the application (production)
yarn start:dev Start with nodemon (development)
yarn build Build TypeScript to JavaScript
yarn db:start Start PostgreSQL Docker container
yarn db:stop Stop PostgreSQL Docker container
yarn db:generate Generate Prisma client
yarn db:migrate Create and apply migrations
yarn db:deploy Deploy migrations (production)

πŸ—οΈ Architecture

MVC Pattern

  • Models: Prisma schema definitions
  • Views: JSON API responses
  • Controllers: Handle HTTP requests/responses
  • Services: Business logic layer

Middleware Stack

  1. Morgan (HTTP logging)
  2. Helmet (Security headers)
  3. CORS (Cross-origin resource sharing)
  4. Body parsers (JSON, URL-encoded)
  5. Compression (Gzip)
  6. Cookie parser
  7. Routes
  8. Error handler

Error Handling

  • Custom HttpException class for structured errors
  • Centralized error handler middleware
  • tryCatchAsync wrapper for async route handlers

Logging

  • Winston logger with daily rotation
  • Logs stored in logs/application-YYYY-MM-DD.log
  • Console output with colorization
  • Automatic log compression and retention (14 days)

Retry Logic

  • Built-in retry utility with configurable attempts (default: 3)
  • Automatic exponential backoff (2 seconds between retries)
  • Error logging for each retry attempt

Use the retry utility:

import { retryFunction } from "./utils/retry";

const error = await retryFunction(async () => {
  // Your async operation
  await someAsyncOperation();
});

πŸ” Authentication

The boilerplate includes API key authentication middleware. Protect routes by adding the middleware:

import authMiddleware from "../app/middlewares/auth.middleware";

router.post("/protected", authMiddleware.verifyApiKey, controller.handler);

Include the API key in request headers:

api-key: your_api_key_here

🌐 Blockchain Integration

The application includes Cosmos SDK integration for Oraichain:

  • Cosmos Client: Automatically connects on server startup
  • Wallet Management: Encrypted mnemonic with password-based decryption
  • Balance Checking: Automatic balance verification on connection
  • Chain ID Validation: Ensures correct network connection

Access the client globally:

import { cosmosClient, cosmosAddress } from "./services/cosmosClient";

πŸ”” Discord Notifications

The application includes Discord webhook integration for sending notifications:

  • Webhook Client: Automatically connects on server startup
  • Rich Embeds: Color-coded notifications (info, error, warning)
  • Server Context: Includes environment information in notifications

Send notifications:

import { sendDiscordNotification } from "./services/discord";

await sendDiscordNotification(
  "Alert Title",
  "Alert description",
  "Additional content",
  "error" // or "info" | "warning"
);

Access the client globally:

import { discordClient } from "./services/discord";

πŸ“¦ Database Schema

User Model

model user {
  id        String   @id @default(uuid())
  name      String
  email     String   @unique
  password  String
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt
}

πŸ§ͺ Example API Usage

Create User

curl -X POST http://localhost:8000/v1/user \
  -H "Content-Type: application/json" \
  -H "api-key: your_api_key_here" \
  -d '{
    "name": "John Doe",
    "email": "[email protected]",
    "password": "securepassword123"
  }'

πŸ”’ Security Features

  • Helmet: Sets various HTTP headers for security
  • CORS: Configurable cross-origin resource sharing
  • API Key Authentication: Protect routes with API keys
  • Encrypted Mnemonics: Secure blockchain wallet storage
  • Input Validation: Joi-based environment validation

πŸ“„ License

MIT License - see LICENSE file for details

πŸ‘€ Author

ledanghuy1811

🀝 Contributing

Contributions, issues, and feature requests are welcome! Feel free to check the issues page.

πŸ“ Notes

  • Prisma client is generated to generated/prisma/ directory
  • Logs are automatically rotated daily and compressed
  • BigInt values are automatically serialized to strings in JSON responses
  • The application gracefully handles SIGTERM and SIGINT signals for clean shutdowns
  • Discord webhook client connects automatically on server startup
  • Retry utility provides resilient error handling for async operations

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published