A robust, secure, and well-tested RESTful API built with Express.js, featuring authentication, protected routes, and comprehensive test coverage. This sample project demonstrates best practices for building Node.js APIs.
- NodeForge API
- Authentication System: Secure signup and login functionality with JWT
- Protected Routes: Middleware for securing endpoints
- API Documentation: Interactive Swagger UI documentation
- Error Handling: Centralized error handling mechanism
- Environment Configuration: Environment-based configuration
- Logging: HTTP request logging with Morgan
- Testing: Comprehensive test suite with Jest
- Code Coverage: High test coverage (>95%)
- Docker Support: Containerized deployment with secure Alpine Linux image
- CI/CD Ready: Easy integration with CI/CD pipelines
- Runtime: Node.js
- Framework: Express.js
- Authentication: JSON Web Tokens (JWT)
- API Documentation: Swagger UI + OpenAPI
- Logging: Morgan
- Testing: Jest + Supertest
- Environment Variables: dotenv
- Containerization: Docker + Docker Compose
The project follows a feature-based structure for better organization and scalability:
.
├── docs/ # Documentation files
│ └── openapi.yaml # OpenAPI/Swagger specification
├── src/ # Source code
│ ├── api/ # API entry point
│ │ └── index.js # Express app setup and server initialization
│ ├── config/ # Configuration files
│ │ └── index.js # Environment variables and app configuration
│ ├── core/ # Core components
│ │ ├── errorHandler.js # Global error handling middleware
│ │ └── logger.js # HTTP request logger
│ └── features/ # Feature modules
│ └── auth/ # Authentication feature
│ ├── controllers/ # Request handlers
│ ├── middleware/ # Auth middleware
│ ├── repositories/ # Data access layer
│ ├── routes/ # Route definitions
│ └── services/ # Business logic
├── tests/ # Test files
│ ├── unit/ # Unit tests
│ │ ├── api/ # API tests
│ │ ├── core/ # Core component tests
│ │ └── features/ # Feature tests
│ ├── auth.test.js # Authentication integration tests
│ └── root.test.js # Root endpoint tests
├── .env # Environment variables (not in version control)
├── .gitignore # Git ignore file
├── nodemon.json # Nodemon configuration
├── package.json # Project dependencies and scripts
└── README.md # Project documentation
- Node.js (v14 or higher)
- npm (v6 or higher)
- Docker (optional, for containerized deployment)
-
Clone the repository:
git clone https://github.com/cristianoaredes/NodeForge-API.git cd NodeForge-API
-
Install dependencies:
npm install
Create a .env
file in the root directory with the following variables:
PORT=3001
JWT_SECRET=your_jwt_secret_key
npm run dev
This will start the server with nodemon for automatic reloading on file changes.
npm start
You can also run the application using Docker:
# Build and start the container
docker-compose up -d
# View logs
docker logs nodeforge-api
# Stop the container
docker-compose down
The Docker setup includes:
- Multi-stage builds for smaller images
- Non-root user for improved security
- Alpine Linux base image with minimal vulnerabilities
- Health checks for container monitoring
Once the application is running, you can access the Swagger UI documentation at:
http://localhost:3001/docs
Method | Endpoint | Description | Authentication |
---|---|---|---|
GET | / | API status check | No |
POST | /auth/signup | Create a new user | No |
POST | /auth/login | Authenticate user and get token | No |
GET | /protected | Access protected resource | Yes |
-
POST /auth/signup
Request body:{ "email": "[email protected]", "password": "password123" }
Response:
{ "email": "[email protected]" }
-
POST /auth/login
Request body:{ "email": "[email protected]", "password": "password123" }
Response:
{ "token": "<JWT token>" }
-
GET /
ReturnsAPI is running
GET /protected
Requires header:Response:Authorization: Bearer <token>
{ "message": "Protected resource", "user": { "email": "[email protected]" } }
# Run all tests
npm test
# Run tests with coverage report
npm test -- --coverage
- Unit Tests: Test individual components in isolation
- Integration Tests: Test API endpoints and their interactions
The project maintains high test coverage:
- Statements: 96.84%
- Branches: 83.33%
- Functions: 92.3%
- Lines: 96.8%
- Signup: Users register with email and password
- Login: Users authenticate and receive a JWT token
- Protected Routes: JWT token is verified for access to protected resources
The application uses a centralized error handling mechanism that:
- Captures all errors thrown in async/await functions
- Returns appropriate HTTP status codes
- Provides meaningful error messages
- Passwords should be hashed before storage in a production environment
- JWT secrets should be strong and kept secure
- Environment variables should be properly managed
- Docker container runs as a non-root user for added security
- Alpine Linux image with minimal attack surface
The application is containerized with Docker using best practices:
- Multi-stage builds: Separates build dependencies from runtime dependencies
- Security: Runs as non-root user (nodejs)
- Base Image: Uses Alpine Linux for minimal size and security vulnerabilities
- Health Checks: Configured to monitor container health
- Docker Compose: Easy orchestration with
docker-compose.yml
The following roadmap outlines the planned enhancements to transform this project into a fully production-ready API base:
Database Integration
- Implementation of ORM/ODM with Mongoose or Sequelize
- Proper connection pooling and error handling
- Database migration capabilities
- Transition from in-memory to database storage
Enhanced Security
- CORS configuration and security headers with Helmet
- Rate limiting for public endpoints
- CSRF protection
- Advanced password hashing
- IP-based blocking for failed auth attempts
Advanced Validation
- Request validation using Joi or express-validator
- Custom error messages for validation failures
- Integration with OpenAPI documentation
Enhanced Logging & Monitoring
- Structured, level-based logging with Winston or Pino
- Request ID tracking across request lifecycle
- Health check endpoints with detailed status monitoring
- Performance metrics collection
API Versioning
- Implementation of versioning strategy (URL, header, or content negotiation)
- Route structure supporting multiple API versions
- Version-specific documentation
- Upgrade path guidance for API consumers
Documentation Enhancements
- Enhanced Swagger/OpenAPI documentation with examples
- Postman collection for API testing
- Architecture diagrams
- Code documentation standards
- Developer onboarding guide
Environment Configuration
- Robust environment variable validation
- Environment-specific configurations
- Secure secrets management
- Comprehensive setup documentation
CI/CD Pipeline
- Automated testing with GitHub Actions
- Linting and code quality checks
- Security vulnerability scanning
- Automated Docker image building and publishing
- Deployment workflow automation
Caching Layer
- Implementation of Redis or in-memory caching
- TTL-based cache management
- Cache invalidation strategies
- Distributed caching support
- Rate limit optimization
Error Handling Improvements
- Standardized error response structure
- Custom error classes for different scenarios
- Centralized error codes and messages
- Localization support for error messages
- Enhanced error context logging
For a detailed breakdown of these enhancements, see the PLAN.md and TODO.md files in the repository.
Contributions are welcome! Please feel free to submit a Pull Request.
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature
) - Commit your changes (
git commit -m 'Add some amazing feature'
) - Push to the branch (
git push origin feature/amazing-feature
) - Open a Pull Request
This project is licensed under the MIT License - see the LICENSE file for details.
For suggestions, questions, or contributions:
- 📧 Email: [email protected]
- 💼 LinkedIn: Cristiano Aredes
If this project has helped you in any way, consider:
- ⭐ Giving it a star on GitHub
- 🐛 Reporting bugs or suggesting improvements in Issues
- 🔀 Forking and contributing to the project
- 📢 Sharing it with other developers
If you use this project as a reference in articles or studies, please cite:
@software{nodeforge_api,
author = {Cristiano Aredes},
title = {NodeForge API},
year = {2025},
publisher = {GitHub},
url = {https://github.com/cristianoaredes/NodeForge-API}
}
The project is hosted on GitHub at https://github.com/cristianoaredes/NodeForge-API.
Feel free to:
- Star the repository if you find it useful
- Fork it to create your own version
- Submit issues or pull requests to contribute
- Use it as a template for your own Node.js API projects
🔍 Keywords: nodejs, express, api, rest, jwt, authentication, docker, testing, swagger, openapi, clean-architecture, feature-based
Made with ❤️ by Cristiano Aredes