Clone the repo:
git clone https://github.com/MuhamedMagdi/express-boilerplate.gitInstall the dependencies:
npm iSet the environment variables:
cp .env.example .env
# open .env and modify the environment variables (if needed)- NoSQL database: MongoDB object data modeling using Mongoose
- Authentication and authorization
- Error handling: centralized error handling mechanism
- API documentation: Postman documentation
- Santizing: sanitize request data against xss and query injection
- Docker support
- Linting: with ESLint and Prettier
Running locally:
npm run devRunning in production:
npm startDocker:
# building the server image
sudo docker build -t server:v1 .
# run docker container
sudo docker-compose upLinting:
# run ESLint
npm run lint:check
# fix ESLint errors
npm run lint:fix
# run prettier
npm run format:check
# fix prettier errros
npm run format:writesrc/
├── config # ENV and global configurations
├── controllers # Route controllers
├── database # Database connection
├── models # Mongoose models
├── routes # API routes
└── utils # General purpose utility function and classes
Go here to view the list of available APIs and their specifications.
The app has a centralized error handling mechanism.
Controllers should try to catch the errors and forward them to the error handling middleware (by calling next(error)). For convenience, you can also wrap the controller inside the catchAsync utility wrapper, which forwards the error.
const catchAsync = require('../utils/catchAsync');
const AppError = require('../utils/appError');
const controller = catchAsync(async (req, res, next) => {
// this error will be forwarded to the error handling middleware
next(new AppError('your error message', your_status_code));
});When running in development mode, the error response also contains the error stack.
Use protect middleware protect certain route to only logged in users.
const { protect } = require('../controllers/authController');
router.post('/some-route-you-want-to-protect', protect, someController);Use restrictTo middleware to restrict certain route to specific logged in users, restrictTo should always be used after the protect middleware.
const { protect, restrictTo } = require('../controllers/authController');
router.post('/some-route-you-want-to-give-access-only-to-admins-and-managers', protect, restrictTo('admin', 'manager'), someController);