node-app-generator
v1.0.5
Published
REST API starter project with authentication, upload and basic APIS required to start with a backend project.
Downloads
9
Maintainers
Readme
RESTful API Node Server Boilerplate / Starter Project
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, API documentation, pagination, image upload etc. For more details, check the features list below.
Quick Start
To create a project, simply run:
npx node-app-generator <project-name>
Or
npm init node-app-generator <project-name>
Manual Installation
If you would still prefer to do the installation manually, follow these steps:
Clone the repo:
git clone --depth 1 https://github.com/tazimmadre/create-node-app.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)
Table of Contents
- Features
- Commands
- Environment Variables
- Project Structure
- Authentication
- Custom Mongoose Plugins
- Linting
- Contributing
Features
- NoSQL database: MongoDB object data modeling using Mongoose
- Authentication and authorization: using passport
- Error handling: centralized error handling mechanism
- Dependency management: with Yarn
- Environment variables: using dotenv and cross-env
- Security: set security HTTP headers using helmet
- Santizing: sanitize request data against xss and query injection
- CORS: Cross-Origin Resource-Sharing enabled using cors
- Compression: gzip compression with compression
Commands
Running locally:
yarn dev
Running in production:
yarn start
Linting:
# run ESLint
yarn lint
# fix ESLint errors
yarn lint:fix
Environment Variables
The environment variables can be found and modified in the .env
file. They come with these default values:
# JWT
# JWT secret key
JWT_SECRET=b1f71e593b42d7af5f27cd2441a186ba7957cc46395086ebdea91417c2187f57
# URL of the Mongo DB
MONGO_CONNECTION_STRING=mongodb://127.0.0.1:27017/test
# Node env
NODE_ENV=development
# Port Number
PORT= 3000
# SEND_Grid
SEND_Grid=SEND_Grid_API
# AWS S3
AWS_ACCESS_KEY_ID=AWS_ACCESS_KEY_ID
AWS_SECRET_ACCESS_KEY=AWS_SECRET_ACCESS_KEY
AWS_REGION=AWS_REGION
# Cloudinary
CLOUDINARY_CLOUD_NAME=CLOUDINARY_CLOUD_NAME
CLOUDINARY_API_KEY=CLOUDINARY_API_KEY
CLOUDINARY_API_SECRET=CLOUDINARY_API_SECRET
Project Structure
src\
|--config\ # Environment variables and configuration related things
|--controllers\ # Route controllers (controller layer)
|--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
util\
|--all files related to utility functions
API Endpoints
List of available routes:
Auth routes:
GET /
POST /upload
POST /register
POST /login
GET /api/user
PUT /api/user
DELETE /api/user
GET /api/user/getUser/:id
POST /api/user/password
PUT /changePassword
POST /admin-register
POST /admin-login
Error Handling
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');
}
};
Validation
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);
Authentication
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', requiresLogin, 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.
Linting
Linting is done using ESLint and Prettier.
To modify the ESLint configuration, update the .eslintrc.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
Contributing
Contributions are more than welcome! Please check out the contributing guide.
Inspirations
- danielfsousa/express-rest-es2017-boilerplate
- madhums/node-express-mongoose
- kunalkapadia/express-mongoose-es6-rest-api