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:
npx create-nodejs-express-app <project-name>
Or
npm init nodejs-express-app <project-name>
If you would still prefer to do the installation manually, follow these steps:
Clone the repo:
git clone --depth 1 https://github.com/hagopj13/node-express-boilerplate.git
cd node-express-boilerplate
npx rimraf ./.git
Install the dependencies:
yarn install
Set the environment variables:
cp .env.example .env
# open .env and modify the environment variables (if needed)
Running locally:
yarn dev
Running in production:
yarn start
Testing:
# run all tests
yarn test
# run all tests in watch mode
yarn test:watch
# run test coverage
yarn coverage
Docker:
# run docker container in development mode
yarn docker:dev
# run docker container in production mode
yarn docker:prod
# run all tests in a docker container
yarn docker:test
Linting:
# run ESLint
yarn lint
# fix ESLint errors
yarn lint:fix
# run prettier
yarn prettier
# fix prettier errors
yarn prettier:fix
The environment variables can be found and modified in the .env
file. They come with these default values:
# Port number
PORT=3000
# URL of the Mongo DB
MONGODB_URL=mongodb://127.0.0.1:27017/node-boilerplate
# JWT
# JWT secret key
JWT_SECRET=thisisasamplesecret
# Number of minutes after which an access token expires
JWT_ACCESS_EXPIRATION_MINUTES=30
# Number of days after which a refresh token expires
JWT_REFRESH_EXPIRATION_DAYS=30
# SMTP configuration options for the email service
# For testing, you can use a fake SMTP service like Ethereal: https://ethereal.email/create
SMTP_HOST=email-server
SMTP_PORT=587
SMTP_USERNAME=email-server-username
SMTP_PASSWORD=email-server-password
EMAIL_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
- registerPOST /v1/auth/login
- loginPOST /v1/auth/refresh-tokens
- refresh auth tokensPOST /v1/auth/forgot-password
- send reset password emailPOST /v1/auth/reset-password
- reset passwordPOST /v1/auth/send-verification-email
- send verification emailPOST /v1/auth/verify-email
- verify email
User routes:POST /v1/users
- create a userGET /v1/users
- get all usersGET /v1/users/:userId
- get userPATCH /v1/users/:userId
- update userDELETE /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.
const catchAsync = require('../utils/catchAsync');
const controller = catchAsync(async (req, res) => {
// this error will be forwarded to the error handling middleware
throw new Error('Something wrong happened');
});
The error handling middleware sends an error response, which has the following format:
{
"code": 404,
"message": "Not found"
}
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:
const httpStatus = require('http-status');
const ApiError = require('../utils/ApiError');
const User = require('../models/User');
const getUser = async (userId) => {
const user = await User.findById(userId);
if (!user) {
throw new ApiError(httpStatus.NOT_FOUND, 'User not found');
}
};
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.
const express = require('express');
const validate = require('../../middlewares/validate');
const userValidation = require('../../validations/user.validation');
const userController = require('../../controllers/user.controller');
const router = express.Router();
router.post('/users', validate(userValidation.createUser), userController.createUser);
To require authentication for certain routes, you can use the auth
middleware.
const express = require('express');
const auth = require('../../middlewares/auth');
const userController = require('../../controllers/user.controller');
const router = express.Router();
router.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.
const express = require('express');
const auth = require('../../middlewares/auth');
const userController = require('../../controllers/user.controller');
const router = express.Router();
router.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):
const logger = require('<path to src>/config/logger');
logger.error('message'); // level 0
logger.warn('message'); // level 1
logger.info('message'); // level 2
logger.http('message'); // level 3
logger.verbose('message'); // level 4
logger.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
.
const mongoose = require('mongoose');
const { toJSON, paginate } = require('./plugins');
const userSchema = mongoose.Schema(
{
/* schema definition here */
},
{ timestamps: true }
);
userSchema.plugin(toJSON);
userSchema.plugin(paginate);
const 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:
const queryUsers = async (filter, options) => {
const users = await User.paginate(filter, options);
return users;
};
The filter
param is a regular mongo filter.
The options
param can have the following (optional) fields:
const options = {
sortBy: 'name:desc', // sort order
limit: 5, // maximum results per page
page: 2, // page number
};
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:
{
"results": [],
"page": 2,
"limit": 5,
"totalPages": 10,
"totalResults": 48
}
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.
express简介 Express是一个简洁、灵活的node.js Web应用开发框架, 它提供一系列强大的功能,比如:模板解析、静态文件服务、中间件、路由控制等等,并且还可以使用插件或整合其他模块来帮助你创建各种 Web和移动设备应用,是目前最流行的基于Node.js的Web开发框架,并且支持Ejs、jade等多种模板,可以快速地搭建一个具有完整功能的网站。 Express 框架核心特性: 可以
express 安装 配置 接收请求 响应 简单的服务器 08express1/server.js const express = require('express'); var server = express();//创建服务 //请求根目录执行 server.use('/a.html',function(req,res){ res.send('aa
所谓中间件,就是一个函数。 Express server 正常的执行流程: HTTP 请求 -> 执行 route handler 但是使用中间件可以在这个流程的中间执行额外的代码: HTTP 请求 -> do something(中间件) -> 执行 route handler 可以使用中间件完成用户认证等操作。 例如当网站在进行维护时,可以使用中间件拦截一切HTTP请求,告知网站正在维护,无法
在centos7安装node.js和express实现webpack打包的前端项目部署运行 1.首先更换国内的yum源 备份 mv /etc/yum.repos.d/CentOS-Base.repo /etc/yum.repos.d/CentOS-Base.repo.backup 下载网易的镜像 cd /etc/yum.repos.d/ wget http://mirrors.163.c
express模块 一、创建web服务器 先下载express模块:npm install express 然后引入express模块 //引入express模块 const express=require('express'); //创建web服务器 const app=express(); //设置端口 app.listen(8080,()=>{ console.log('服务器创
Express 什么是 Express? Express 是基于 Node.js 平台, 快速,开放,极简的 Web 开发框架 基本使用 安装 在项目所处的根目录中运行: npm i express@4.17.1 创建基本的 Web 服务器 //导入 express const express = require('express') // 创建 web 服务器 const app = expr
get方法 —— 根据请求路径来处理客户端发出的GET请求。 格式:app.get(path,function(request, response)); path为请求的路径,第二个参数为处理请求的回调函数,有两个参数分别是request和response,代表请求信息和响应信息。 如下示例: var express = require('express'); var app = express(
总结 安装cookie中间件 cookie是一种存储数据的方法 使用cookie可以将数组存储起来 他是可以在客户端和服务端穿梭的数据 安装命令 yarn add cookie-parser --save 使用cookie 在要使用cookie的js文件中 var express = require('express'); var app = express() var
安装express框架 cnpm install --save-dev express 配置框架路由 express 框架里面的路由 all用于所有的http请求 类似每个路由的安全守卫 路由守卫提前路由执行 next() 方法下一步 模拟express框架路由 实现: let http = require("http"); let app = require('./route'); let e
RESTful API Server Boilerplate Featuring Docker, Node, Express, MongoDB, Mongoose, & NGINX License & Purpose MIT License. This is something I've used in production before with success that I found use
Node.jsを使ってアプリケーションを構築しよう 目次 アプリケーションの構造を理解しよう Node.jsについて知ろう Node.jsを使ってみよう Node.jsとExpressの基本 MySQLを使ってデータベースを構築しよう Node.jsとデータベースを接続しよう Node.jsでデータベースからデータを取得して表示させてみよう Node.jsで詳細ページを作ってみよう Node.js
Node.js Express & MongoDB: CRUD Rest APIs For more detail, please visit: Node.js, Express & MongoDb: Build a CRUD Rest Api example Server side Pagination in Node.js with MongoDB and Mongoose Security:
Node Express Mongoose A boilerplate application for building web apps using express, mongoose and passport. Read the wiki to understand how the application is structured. Usage git clone https://githu
node-weixin-express是一个基于nodejs为基础,以expressjs作为首选http服务器框架的微信公共账号服务器。 他旨在降低开发微信公共账号时的门槛,节约开发时间。 几个主要目标: 可以直接通过一个命令运行微信公共账号服务(已经完成) 实现基本的微信功能: 验证服务器(已经完成) OAuth 验证API(已经完成) 微信支付API(已经完成) 消息接口API(等待完成) 可
Node.js, Express.js, Sequelize.js and PostgreSQL RESTful API This source code is part of Node.js, Express.js, Sequelize.js and PostgreSQL RESTful API tutorial. To run locally: Make sure you have insta