This is a boilerplate template for a secure Express.js backend server with MongoDB integration, JWT authentication, and HTTPS support.
- Express.js server with HTTPS support
- MongoDB integration using Mongoose
- JWT authentication
- Rate limiting
- CORS enabled
- Body parsing
- Logging with morgan and mercedlogger
- Nodemon for development
- Dockerfile for containerization
- Node.js (v16.20.1 or later recommended)
- MongoDB instance
- OpenSSL for generating SSL certificates
- Clone this repository:
git clone https://github.com/your-username/express-backend-boilerplate.git cd express-backend-boilerplate
- Install dependencies:
npm install
- Set up environment variables:
Create a
.env
file in the root directory with the following content:
PORT=3000 DATABASE_URL=mongodb://admin:YourPassword@your-mongodb-host:27017/your-database?authSource=admin SECRET=your-jwt-secret
Replace YourPassword
, your-mongodb-host
, and your-database
with your actual MongoDB credentials and details.
- Generate SSL certificates:
openssl req -x509 -newkey rsa:4096 -keyout ./ssl/key.pem -out ./ssl/cert.pem -days 365 -nodes
This will create self-signed certificates in the ssl
directory. For production, use certificates from a trusted Certificate Authority.
- Start the server:
- For development:
npm run test
- For production:
npm start
To build and run the application using Docker:
- Build the Docker image:
docker build -t express-backend-boilerplate .
- Run the container:
docker run -p 3000:3000 -v $(pwd):/app express-backend-boilerplate
GET /
: Hello world routePOST /user/signup
: User registrationPOST /user/login
: User loginGET /user/logout
: User logoutGET /protected
: Example protected route (requires authentication)
This boilerplate uses JWT for authentication. To access protected routes, include the JWT token in the Authorization header:
Authorization: Bearer
- Server configuration:
server.js
- Database connection:
middlewares/db.connection.js
- Authentication middleware:
middlewares/global.js
- User model:
models/User.js
- Always use HTTPS in production
- Keep your JWT secret secure and use a strong, unique value
- Regularly update dependencies to patch security vulnerabilities
- Use environment variables for sensitive information, never commit them to version control
Contributions are welcome! Please feel free to submit a Pull Request.
This project is licensed under the ISC License.