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.
- 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
- Node.js (v18 or higher)
- Yarn (v1.22 or higher) or npm
- Docker and Docker Compose (for local database)
- PostgreSQL (or use Docker Compose)
- Express ^5.2.1 - Web framework
- TypeScript ^5.9.3 - Type safety
- Prisma ^7.2.0 - Database ORM
- PostgreSQL - Database
- @cosmjs/cosmwasm-stargate ^0.38.1 - Cosmos SDK client
- @cosmjs/proto-signing ^0.38.1 - Transaction signing
- @cosmjs/amino ^0.38.1 - Amino encoding
- 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
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
-
Clone the repository
git clone [email protected]:ledinhhuy1811/nodejs-boilerplate.git cd nodejs-boilerplate
-
Install dependencies
yarn install # or npm install -
Set up environment variables Create a
.envfile 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
-
Start the database
yarn db:start
-
Run database migrations
yarn db:migrate
-
Generate Prisma client
yarn db:generate
| 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 | - |
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_MNEMONICyarn start:dev
# or
npm run start:devyarn build
yarn start
# or
npm run build
npm startOnce the server is running, check the health endpoint:
curl http://localhost:8000/healthSwagger 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.
yarn db:startyarn db:stopyarn db:migrateyarn db:deployyarn db:generate| 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) |
- Models: Prisma schema definitions
- Views: JSON API responses
- Controllers: Handle HTTP requests/responses
- Services: Business logic layer
- Morgan (HTTP logging)
- Helmet (Security headers)
- CORS (Cross-origin resource sharing)
- Body parsers (JSON, URL-encoded)
- Compression (Gzip)
- Cookie parser
- Routes
- Error handler
- Custom
HttpExceptionclass for structured errors - Centralized error handler middleware
tryCatchAsyncwrapper for async route handlers
- 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)
- 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();
});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
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";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";model user {
id String @id @default(uuid())
name String
email String @unique
password String
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}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"
}'- 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
MIT License - see LICENSE file for details
ledanghuy1811
- Email: [email protected]
- GitHub: @ledinhhuy1811
Contributions, issues, and feature requests are welcome! Feel free to check the issues page.
- 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