Gathering detailed insights and metrics for create-nodejs-express-app
Gathering detailed insights and metrics for create-nodejs-express-app
Gathering detailed insights and metrics for create-nodejs-express-app
Gathering detailed insights and metrics for create-nodejs-express-app
create-express-mvc-app
Custom Express app generator
@phazero/create-express-app
A basic cli that creates a backend service.
create-desk-native-app
A full-stack framework for building native desktop applications with web technologies.
create-nodejs-ts-app
Node express mongoose typescript boilerplate
A boilerplate for building production-ready RESTful APIs using Node.js, Express, and Mongoose
npm install create-nodejs-express-app
Typescript
Module System
Min. Node Version
Node Version
NPM Version
JavaScript (99.65%)
Dockerfile (0.2%)
Shell (0.14%)
Total Downloads
0
Last Day
0
Last Week
0
Last Month
0
Last Year
0
MIT License
7,388 Stars
241 Commits
2,158 Forks
102 Watchers
16 Branches
15 Contributors
Updated on Jul 13, 2025
Latest Version
1.7.0
Package Id
create-nodejs-express-app@1.7.0
Unpacked Size
148.53 kB
Size
33.64 kB
File Count
76
NPM Version
6.14.7
Node Version
14.8.0
Cumulative downloads
Total Downloads
Last Day
0%
NaN
Compared to previous day
Last Week
0%
NaN
Compared to previous week
Last Month
0%
NaN
Compared to previous month
Last Year
0%
NaN
Compared to previous year
24
A boilerplate/starter project for quickly building RESTful APIs using Node.js, Express, and Mongoose.
By running a single command, you will get a production-ready Node.js app installed and fully configured on your machine. The app comes with many built-in features, such as authentication using JWT, request validation, unit and integration tests, continuous integration, docker support, API documentation, pagination, etc. For more details, check the features list below.
To create a project, simply run:
1npx create-nodejs-express-app <project-name>
Or
1npm init nodejs-express-app <project-name>
If you would still prefer to do the installation manually, follow these steps:
Clone the repo:
1git clone --depth 1 https://github.com/hagopj13/node-express-boilerplate.git 2cd node-express-boilerplate 3npx rimraf ./.git
Install the dependencies:
1yarn install
Set the environment variables:
1cp .env.example .env 2 3# open .env and modify the environment variables (if needed)
Running locally:
1yarn dev
Running in production:
1yarn start
Testing:
1# run all tests 2yarn test 3 4# run all tests in watch mode 5yarn test:watch 6 7# run test coverage 8yarn coverage
Docker:
1# run docker container in development mode 2yarn docker:dev 3 4# run docker container in production mode 5yarn docker:prod 6 7# run all tests in a docker container 8yarn docker:test
Linting:
1# run ESLint 2yarn lint 3 4# fix ESLint errors 5yarn lint:fix 6 7# run prettier 8yarn prettier 9 10# fix prettier errors 11yarn prettier:fix
The environment variables can be found and modified in the .env
file. They come with these default values:
1# Port number 2PORT=3000 3 4# URL of the Mongo DB 5MONGODB_URL=mongodb://127.0.0.1:27017/node-boilerplate 6 7# JWT 8# JWT secret key 9JWT_SECRET=thisisasamplesecret 10# Number of minutes after which an access token expires 11JWT_ACCESS_EXPIRATION_MINUTES=30 12# Number of days after which a refresh token expires 13JWT_REFRESH_EXPIRATION_DAYS=30 14 15# SMTP configuration options for the email service 16# For testing, you can use a fake SMTP service like Ethereal: https://ethereal.email/create 17SMTP_HOST=email-server 18SMTP_PORT=587 19SMTP_USERNAME=email-server-username 20SMTP_PASSWORD=email-server-password 21EMAIL_FROM=support@yourapp.com
src\
|--config\ # Environment variables and configuration related things
|--controllers\ # Route controllers (controller layer)
|--docs\ # Swagger files
|--middlewares\ # Custom express middlewares
|--models\ # Mongoose models (data layer)
|--routes\ # Routes
|--services\ # Business logic (service layer)
|--utils\ # Utility classes and functions
|--validations\ # Request data validation schemas
|--app.js # Express app
|--index.js # App entry point
To view the list of available APIs and their specifications, run the server and go to http://localhost:3000/v1/docs
in your browser. This documentation page is automatically generated using the swagger definitions written as comments in the route files.
List of available routes:
Auth routes:
POST /v1/auth/register
- register
POST /v1/auth/login
- login
POST /v1/auth/refresh-tokens
- refresh auth tokens
POST /v1/auth/forgot-password
- send reset password email
POST /v1/auth/reset-password
- reset password
POST /v1/auth/send-verification-email
- send verification email
POST /v1/auth/verify-email
- verify email
User routes:
POST /v1/users
- create a user
GET /v1/users
- get all users
GET /v1/users/:userId
- get user
PATCH /v1/users/:userId
- update user
DELETE /v1/users/:userId
- delete user
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.
1const catchAsync = require('../utils/catchAsync'); 2 3const controller = catchAsync(async (req, res) => { 4 // this error will be forwarded to the error handling middleware 5 throw new Error('Something wrong happened'); 6});
The error handling middleware sends an error response, which has the following format:
1{ 2 "code": 404, 3 "message": "Not found" 4}
When running in development mode, the error response also contains the error stack.
The app has a utility ApiError class to which you can attach a response code and a message, and then throw it from anywhere (catchAsync will catch it).
For example, if you are trying to get a user from the DB who is not found, and you want to send a 404 error, the code should look something like:
1const httpStatus = require('http-status'); 2const ApiError = require('../utils/ApiError'); 3const User = require('../models/User'); 4 5const getUser = async (userId) => { 6 const user = await User.findById(userId); 7 if (!user) { 8 throw new ApiError(httpStatus.NOT_FOUND, 'User not found'); 9 } 10};
Request data is validated using Joi. Check the documentation for more details on how to write Joi validation schemas.
The validation schemas are defined in the src/validations
directory and are used in the routes by providing them as parameters to the validate
middleware.
1const express = require('express'); 2const validate = require('../../middlewares/validate'); 3const userValidation = require('../../validations/user.validation'); 4const userController = require('../../controllers/user.controller'); 5 6const router = express.Router(); 7 8router.post('/users', validate(userValidation.createUser), userController.createUser);
To require authentication for certain routes, you can use the auth
middleware.
1const express = require('express'); 2const auth = require('../../middlewares/auth'); 3const userController = require('../../controllers/user.controller'); 4 5const router = express.Router(); 6 7router.post('/users', auth(), userController.createUser);
These routes require a valid JWT access token in the Authorization request header using the Bearer schema. If the request does not contain a valid access token, an Unauthorized (401) error is thrown.
Generating Access Tokens:
An access token can be generated by making a successful call to the register (POST /v1/auth/register
) or login (POST /v1/auth/login
) endpoints. The response of these endpoints also contains refresh tokens (explained below).
An access token is valid for 30 minutes. You can modify this expiration time by changing the JWT_ACCESS_EXPIRATION_MINUTES
environment variable in the .env file.
Refreshing Access Tokens:
After the access token expires, a new access token can be generated, by making a call to the refresh token endpoint (POST /v1/auth/refresh-tokens
) and sending along a valid refresh token in the request body. This call returns a new access token and a new refresh token.
A refresh token is valid for 30 days. You can modify this expiration time by changing the JWT_REFRESH_EXPIRATION_DAYS
environment variable in the .env file.
The auth
middleware can also be used to require certain rights/permissions to access a route.
1const express = require('express'); 2const auth = require('../../middlewares/auth'); 3const userController = require('../../controllers/user.controller'); 4 5const router = express.Router(); 6 7router.post('/users', auth('manageUsers'), userController.createUser);
In the example above, an authenticated user can access this route only if that user has the manageUsers
permission.
The permissions are role-based. You can view the permissions/rights of each role in the src/config/roles.js
file.
If the user making the request does not have the required permissions to access this route, a Forbidden (403) error is thrown.
Import the logger from src/config/logger.js
. It is using the Winston logging library.
Logging should be done according to the following severity levels (ascending order from most important to least important):
1const logger = require('<path to src>/config/logger'); 2 3logger.error('message'); // level 0 4logger.warn('message'); // level 1 5logger.info('message'); // level 2 6logger.http('message'); // level 3 7logger.verbose('message'); // level 4 8logger.debug('message'); // level 5
In development mode, log messages of all severity levels will be printed to the console.
In production mode, only info
, warn
, and error
logs will be printed to the console.
It is up to the server (or process manager) to actually read them from the console and store them in log files.
This app uses pm2 in production mode, which is already configured to store the logs in log files.
Note: API request information (request url, response code, timestamp, etc.) are also automatically logged (using morgan).
The app also contains 2 custom mongoose plugins that you can attach to any mongoose model schema. You can find the plugins in src/models/plugins
.
1const mongoose = require('mongoose'); 2const { toJSON, paginate } = require('./plugins'); 3 4const userSchema = mongoose.Schema( 5 { 6 /* schema definition here */ 7 }, 8 { timestamps: true } 9); 10 11userSchema.plugin(toJSON); 12userSchema.plugin(paginate); 13 14const User = mongoose.model('User', userSchema);
The toJSON plugin applies the following changes in the toJSON transform call:
The paginate plugin adds the paginate
static method to the mongoose schema.
Adding this plugin to the User
model schema will allow you to do the following:
1const queryUsers = async (filter, options) => { 2 const users = await User.paginate(filter, options); 3 return users; 4};
The filter
param is a regular mongo filter.
The options
param can have the following (optional) fields:
1const options = { 2 sortBy: 'name:desc', // sort order 3 limit: 5, // maximum results per page 4 page: 2, // page number 5};
The plugin also supports sorting by multiple criteria (separated by a comma): sortBy: name:desc,role:asc
The paginate
method returns a Promise, which fulfills with an object having the following properties:
1{ 2 "results": [], 3 "page": 2, 4 "limit": 5, 5 "totalPages": 10, 6 "totalResults": 48 7}
Linting is done using ESLint and Prettier.
In this app, ESLint is configured to follow the Airbnb JavaScript style guide with some modifications. It also extends eslint-config-prettier to turn off all rules that are unnecessary or might conflict with Prettier.
To modify the ESLint configuration, update the .eslintrc.json
file. To modify the Prettier configuration, update the .prettierrc.json
file.
To prevent a certain file or directory from being linted, add it to .eslintignore
and .prettierignore
.
To maintain a consistent coding style across different IDEs, the project contains .editorconfig
Contributions are more than welcome! Please check out the contributing guide.
No vulnerabilities found.
Reason
no binaries found in the repo
Reason
license file detected
Details
Reason
Found 5/11 approved changesets -- score normalized to 4
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
Reason
project is not fuzzed
Details
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Reason
54 existing vulnerabilities detected
Details
Score
Last Scanned on 2025-07-07
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More