Template lengkap untuk membangun REST API dengan Express.js yang sudah dilengkapi dengan berbagai fitur esensial untuk pengembangan aplikasi production-ready.
- β Example Module Template: Module contoh lengkap dengan CRUD, pagination, soft delete, validation
- β Database: PostgreSQL dengan Knex.js untuk query builder, migration, dan seeding
- β Authentication Ready: JWT middleware dan utilities (tinggal implement)
- β File Upload: Integrasi dengan AWS S3 dan MinIO untuk object storage
- β Email Service: Template email dengan Nodemailer
- β Message Queue: RabbitMQ untuk async task processing
- β API Documentation: Swagger/OpenAPI 3.0 dengan contoh lengkap
- β Security: Rate limiting, CORS, input validation, XSS protection
- β Monitoring: Prometheus metrics dan comprehensive logging
- β Internationalization: Multi-language support dengan i18n
- β Docker Support: Docker & Docker Compose untuk development dan production
- β CI/CD: Jenkins & Bitbucket Pipelines configuration
Sebelum memulai, pastikan Anda sudah menginstall:
- Node.js (v14 atau lebih baru)
- PostgreSQL (v12 atau lebih baru)
- Redis (opsional, untuk session storage)
- Docker & Docker Compose (opsional, untuk containerization)
git clone https://github.com/your-username/express-api-boilerplate.git
cd express-api-boilerplate
npm install
Copy file environment example dan sesuaikan konfigurasi:
cp environment.example .env
Edit file .env
dan sesuaikan dengan konfigurasi Anda:
# Application
APP_NAME=YourAppName
NODE_ENV=development
PORT=3000
APP_URL=http://localhost:3000
# Database
DB_HOST=localhost
DB_PORT=5432
DB_USER=postgres
DB_PASSWORD=yourpassword
DB_NAME=yourdbname
# JWT
JWT_SECRET=your-secret-key
JWT_EXPIRES_IN=24h
# AWS S3 (optional)
AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
AWS_REGION=
AWS_BUCKET=
# MinIO (optional)
MINIO_ENDPOINT=
MINIO_PORT=
MINIO_ACCESS_KEY=
MINIO_SECRET_KEY=
MINIO_BUCKET=
# Email
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USER=
MAIL_PASSWORD=
MAIL_FROM=
# RabbitMQ (optional)
RABBITMQ_URL=amqp://localhost:5672
# Swagger
SWAGGER_ENABLED=true
Jalankan migration untuk membuat struktur database:
npm run migrate
Jalankan seeder untuk data awal (opsional):
npm run seed
npm run dev
Server akan berjalan di http://localhost:3000
Akses dokumentasi API di http://localhost:3000/documentation
βββ src/
β βββ app.js # Express app configuration
β βββ server.js # Server entry point
β βββ config/ # Konfigurasi aplikasi
β β βββ database.js # Database configuration
β β βββ aws.js # AWS S3 configuration
β β βββ minio.js # MinIO configuration
β β βββ email.js # Email configuration
β β βββ rabbitmq.js # RabbitMQ configuration
β β βββ prometheus.js # Prometheus configuration
β βββ modules/ # Business logic modules
β β βββ example/ # π Example module (TEMPLATE)
β β β βββ handler.js # Controllers
β β β βββ postgre_repository.js # DB operations
β β β βββ validation.js # Validation rules
β β β βββ index.js # Routes
β β β βββ README.md # Documentation
β β βββ helpers/ # Helper functions
β βββ middlewares/ # Custom middlewares
β β βββ token.js # JWT verification
β β βββ validation.js # Input validation
β β βββ rate-limiter.js # Rate limiting
β β βββ recaptcha.js # reCAPTCHA verification
β β βββ fileUpload.js # File upload handling
β βββ routes/ # API routes
β β βββ index.js # Main routes
β β βββ V1/ # API version 1
β βββ repository/ # Database layer
β β βββ postgres/ # PostgreSQL specific
β β βββ migrations/ # Database migrations
β β βββ seeders/ # Database seeders
β βββ utils/ # Utility functions
β β βββ response.js # Standard API response
β β βββ logger.js # Logging utility
β β βββ validation.js # Validation helpers
β β βββ pagination.js # Pagination helper
β β βββ ...
β βββ static/ # Swagger documentation
β β βββ index.js # Swagger config
β β βββ path/ # API path definitions
β β βββ schema/ # Schema definitions
β βββ templates/ # Email templates
β βββ views/ # View templates
β βββ listeners/ # RabbitMQ message listeners
β βββ scripts/ # Background scripts
β βββ debug/ # Debug utilities
βββ docker/ # Docker configurations
βββ public/ # Static files
βββ logs/ # Application logs
βββ uploads/ # Uploaded files
βββ test/ # Test files
βββ scripts/ # Utility scripts
βββ docs/ # Additional documentation
βββ .env # Environment variables (create from .env.example)
βββ package.json # Dependencies
βββ QUICKSTART.md # Quick start guide
βββ CONTRIBUTING.md # Contribution guidelines
βββ README.md # This file
π‘ Tip: Gunakan module
example
sebagai template! Copy dan customize sesuai kebutuhan.
# Copy module example sebagai template
cp -r src/modules/example src/modules/products
# Edit files di src/modules/products:
# - Ganti "example" dengan "product"
# - Ganti "examples" dengan "products"
# - Customize fields sesuai kebutuhan
Buat folder baru di src/modules/namaModule/
Struktur minimal sebuah module:
src/modules/namaModule/
βββ index.js # Export semua handler
βββ handler.js # Request handlers
βββ validation.js # Input validation rules
βββ postgre_repository.js # Database operations
const repository = require('./postgre_repository');
const { baseResponse, errorResponse } = require('../../utils/response');
const getAll = async (req, res) => {
try {
const data = await repository.findAll();
return baseResponse(res, { data });
} catch (error) {
return errorResponse(res, error);
}
};
const getById = async (req, res) => {
try {
const { id } = req.params;
const data = await repository.findById(id);
if (!data) {
return errorResponse(res, { message: 'Data not found' }, 404);
}
return baseResponse(res, { data });
} catch (error) {
return errorResponse(res, error);
}
};
const create = async (req, res) => {
try {
const data = await repository.create(req.body);
return baseResponse(res, { data }, 201);
} catch (error) {
return errorResponse(res, error);
}
};
const update = async (req, res) => {
try {
const { id } = req.params;
const data = await repository.update(id, req.body);
return baseResponse(res, { data });
} catch (error) {
return errorResponse(res, error);
}
};
const remove = async (req, res) => {
try {
const { id } = req.params;
await repository.remove(id);
return baseResponse(res, { message: 'Data deleted successfully' });
} catch (error) {
return errorResponse(res, error);
}
};
module.exports = {
getAll,
getById,
create,
update,
remove
};
const db = require('../../config/database');
const TABLE_NAME = 'your_table_name';
const findAll = async () => {
return await db(TABLE_NAME)
.select('*')
.where({ deleted_at: null })
.orderBy('created_at', 'desc');
};
const findById = async (id) => {
return await db(TABLE_NAME)
.where({ id, deleted_at: null })
.first();
};
const create = async (data) => {
const [result] = await db(TABLE_NAME)
.insert({
...data,
created_at: db.fn.now(),
updated_at: db.fn.now()
})
.returning('*');
return result;
};
const update = async (id, data) => {
const [result] = await db(TABLE_NAME)
.where({ id })
.update({
...data,
updated_at: db.fn.now()
})
.returning('*');
return result;
};
const remove = async (id) => {
// Soft delete
return await db(TABLE_NAME)
.where({ id })
.update({
deleted_at: db.fn.now()
});
};
module.exports = {
findAll,
findById,
create,
update,
remove
};
const { body, param, query } = require('express-validator');
const createValidation = [
body('name')
.notEmpty()
.withMessage('Name is required')
.isLength({ min: 3 })
.withMessage('Name must be at least 3 characters'),
body('email')
.notEmpty()
.withMessage('Email is required')
.isEmail()
.withMessage('Email must be valid'),
];
const updateValidation = [
param('id')
.notEmpty()
.withMessage('ID is required')
.isUUID()
.withMessage('ID must be valid UUID'),
body('name')
.optional()
.isLength({ min: 3 })
.withMessage('Name must be at least 3 characters'),
];
module.exports = {
createValidation,
updateValidation
};
const express = require('express');
const router = express.Router();
const handler = require('./handler');
const { createValidation, updateValidation } = require('./validation');
const { verifyToken } = require('../../middlewares');
const { handleValidationErrors } = require('../../middlewares/validation');
router.get('/', verifyToken, handler.getAll);
router.get('/:id', verifyToken, handler.getById);
router.post('/', verifyToken, createValidation, handleValidationErrors, handler.create);
router.put('/:id', verifyToken, updateValidation, handleValidationErrors, handler.update);
router.delete('/:id', verifyToken, handler.remove);
module.exports = router;
Edit file src/routes/V1/index.js
:
const yourModule = require('../../modules/yourModule');
// ... existing code ...
routing.use(`${API_TAG}/your-endpoint`, yourModule);
Buat file migration untuk table:
npm run migrate:make create_your_table
Edit file migration di src/repository/postgres/migrations/
:
exports.up = function(knex) {
return knex.schema.createTable('your_table_name', (table) => {
table.uuid('id').primary().defaultTo(knex.raw('uuid_generate_v4()'));
table.string('name').notNullable();
table.string('email').unique();
table.text('description');
table.timestamp('created_at').defaultTo(knex.fn.now());
table.timestamp('updated_at').defaultTo(knex.fn.now());
table.timestamp('deleted_at').nullable();
});
};
exports.down = function(knex) {
return knex.schema.dropTable('your_table_name');
};
Jalankan migration:
npm run migrate
Boilerplate ini sudah include module example
sebagai template dengan endpoints berikut:
GET /api/examples?page=1&limit=10
GET /api/examples/:id
POST /api/examples
Content-Type: application/json
{
"name": "Example Name",
"description": "Description",
"status": "active"
}
PUT /api/examples/:id
Content-Type: application/json
{
"name": "Updated Name"
}
DELETE /api/examples/:id
POST /api/examples/:id/restore
π Full API Documentation:
http://localhost:3000/documentation
Boilerplate sudah include JWT middleware. Untuk menggunakannya:
const { verifyToken } = require('../../middlewares');
router.get('/', verifyToken, handler.getAll);
Authorization: Bearer your-jwt-token
π‘ Tip: Lihat
src/middlewares/token.js
untuk JWT verification logic
Dokumentasi API tersedia via Swagger UI. Akses di:
http://localhost:3000/documentation
Untuk menambahkan dokumentasi API Anda, edit file:
src/static/path/yourModule.js
- untuk endpoint pathssrc/static/schema/yourModule.js
- untuk schema definitions
docker-compose -f docker-compose.dev.yml up
docker-compose -f docker-compose.server.yml up -d
Metrics tersedia di endpoint:
http://localhost:3000/metrics
Log tersimpan di folder logs/
:
logs/application/
- Application logslogs/listener/
- RabbitMQ listener logs
npm test
npm start
- Jalankan server productionnpm run dev
- Jalankan server development dengan nodemonnpm run migrate
- Jalankan database migrationsnpm run migrate:rollback
- Rollback migration terakhirnpm run migrate:make <name>
- Buat file migration barunpm run seed
- Jalankan database seedersnpm run seed:make <name>
- Buat file seeder barunpm run consumer
- Jalankan RabbitMQ consumernpm test
- Jalankan tests
- express - Web framework
- pg - PostgreSQL client
- knex - SQL query builder
- jsonwebtoken - JWT implementation
- bcrypt - Password hashing
- joi - Schema validation
- express-validator - Request validation
- morgan - HTTP request logger
- winston - Logging library
- moment - Date manipulation
- uuid - UUID generator
- multer - Multipart/form-data handling
- aws-sdk - AWS S3 client
- minio - MinIO client
- sharp - Image processing
- swagger-ui-express - API documentation
- prom-client - Prometheus metrics
- amqplib - RabbitMQ client
- nodemailer - Email sending
- i18n - Internationalization
- compression - Response compression
- xss-clean - XSS protection
- express-rate-limit - Rate limiting
Contributions are welcome! Silakan buat pull request atau issue untuk saran dan perbaikan.
MIT License - lihat file LICENSE untuk detail.
Your Name
- GitHub: @your-username
- Email: your-email@example.com
Boilerplate ini dibuat dengan menggabungkan best practices dari berbagai sumber dan pengalaman development.
Untuk pertanyaan atau dukungan:
- Buat issue di GitHub Issues
- Email: your-email@example.com
Made with β€οΈ for the developer community