Express Typescript Mongoose Boilerplate
A boilerplate/starter project for quickly building RESTful APIs using Node.js, Express, and Mongoose.
The app comes with many built-in features, such as authentication using JWT, request validation, unit and integration tests, etc.
Quick Start
Clone project to create your project, simply run:
git clone https://github.com/MrBrown6210/nodejs-express-mongoose-typescript-boilerplate.git <project-name>
Set the environment variables:
(You can see all enviroment key at src/config/config)
cp .env.example .env
Feature
Commands
Running locally:
yarn dev
building:
yarn build
Running production (build before use):
yarn start
Testing:
yarn test
yarn test:watch
yarn test:coverage
yarn test:e2e
yarn test:e2e:watch
Enviroment Variable
The environment variables can be found and modified in the .env
file. They come with these default values:
APP_PORT=9000
APP_PREFIX_PATH=/
JWT_SECRET=somerandomkeyherena
JWT_EXPIRE=1y
DB_URI=mongodb://localhost:27017/Mocks
DB_USER=root
DB_USER_PWD=secret
DB_HOST=localhost
DB_NAME=conduit
DB_PORT=27017
Project Structure
This project don't have controllers and services folders because we want to minimalized. If you want them, you can create it
src\
|--config\
|--middlewares\
|--models\
|--routes\
|--utils\
|--app.js
|--index.js
Error handling
The app has a centralized error handling mechanism.
Routes should try to catch the errors and forward them to the error handling middleware (by calling next(e)
).
router.post('/login', async (req, res, next) => {
try {
const { email, password } = req.body
const user = await User.findOne({ email })
if (!user || !user.validPassword(password))
throw new ApiError(httpStatus.UNPROCESSABLE_ENTITY, 'Invalid email or password')
res.json(user.toAuthJSON())
} catch (e) {
next(e)
}
})
The error handling middleware sends an error response, which has the following format:
{
"code": 401,
"message": "Invalid email or password"
}
When running in development mode, the error response also contains the error stack.
Authentication
To require authentication for certain routes, you can use the authenticate
from passportjs
router.post('/', authenticate(['jwt'], { session: false }), async (req, res, next) => {
try {
const store = new Store(req.body.store)
await store.save()
res.json(store)
} catch (e) {
next(e)
}
})
Logging
Import the logger from src/config/logger.ts
. 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):
import logger from '@/config/logger'
logger.error('message');
logger.warn('message');
logger.info('message');
logger.http('message');
logger.verbose('message');
logger.debug('message');
In production mode, only info
, warn
, and error
logs will be printed to the console.
Linting
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
Contributing
Contributions are welcome! Please check out the contributing guide.
Inspirations
License
MIT