Gathering detailed insights and metrics for create-nodejs-ts-app
Gathering detailed insights and metrics for create-nodejs-ts-app
Gathering detailed insights and metrics for create-nodejs-ts-app
Gathering detailed insights and metrics for create-nodejs-ts-app
@shahafc13/create-node-ts-app
A CLI tool to generate Node.js + TypeScript projects from predefined templates.
@canseyran/create-ts-cli-app
Create TypeScript CLI App is a simple and efficient tool to set up a Node.js TypeScript project with minimal hassle. It comes pre-configured with essential tools and libraries, allowing you to focus on writing your code rather than setting up your environ
express-ts-boiler-plate
Basic express Typescript with mongodbConnection Boiler Plate
@onsever/create-express-ts-app
This is a starter template for Express.js with TypeScript that includes Jest, Prettier, ESLint, and more.
A boilerplate for making production-ready RESTful APIs using Node.js, TypeScript, Express, and Mongoose
npm install create-nodejs-ts-app
Typescript
Module System
Min. Node Version
Node Version
NPM Version
TypeScript (96.96%)
JavaScript (2.53%)
Dockerfile (0.34%)
Shell (0.17%)
Total Downloads
0
Last Day
0
Last Week
0
Last Month
0
Last Year
0
MIT License
352 Stars
180 Commits
101 Forks
14 Watchers
26 Branches
5 Contributors
Updated on Jun 25, 2025
Latest Version
3.0.11
Package Id
create-nodejs-ts-app@3.0.11
Unpacked Size
218.23 kB
Size
54.26 kB
File Count
93
NPM Version
6.14.17
Node Version
14.20.1
Published on
Feb 14, 2024
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
43
By running a single command, you will get a production-ready Node.js TypeScript 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.
Node.js has deprecated the --es-module-specifier-resolution=node
flag, used in this app, in the release of Node.js v19 in favor of custom loaders. You can check out the PR here.
As a result, this app is not compatible with Node.js >=19. You can add support to your app using this loader
To create a project, simply run:
1npx create-nodejs-ts-app <project-name>
Or
1npm init nodejs-ts-app <project-name>
Clone the repo:
1git clone --depth 1 https://github.com/saisilinus/node-express-mongoose-typescript-boilerplate.git 2cd node-express-mongoose-typescript-boilerplate
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
Compiling to JS from TS
1yarn compile
Compiling to JS from TS in watch mode
1yarn compile:watch
Commiting changes
1yarn commit
Testing:
1# run all tests 2yarn test 3 4# run TypeScript tests 5yarn test:ts 6 7# run JS tests 8yarn test:js 9 10# run all tests in watch mode 11yarn test:watch 12 13# run test coverage 14yarn 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
Run yarn dev
so you can compile Typescript(.ts) files in watch mode
1yarn dev
Add your changes to TypeScript(.ts) files which are in the src folder. The files will be automatically compiled to JS if you are in watch mode.
Add tests for the new feature
Run yarn test:ts
to make sure all Typescript tests pass.
1yarn test:ts
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/Park254_Backend 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 22 23# URL of client application 24CLIENT_URL=http://localhost:5000
.
├── src # Source files
│ ├── app.ts # Express App
│ ├── config # Environment variables and other configurations
│ ├── custom.d.ts # File for extending types from node modules
│ ├── declaration.d.ts # File for declaring modules without types
│ ├── index.ts # App entry file
│ ├── modules # Modules such as models, controllers, services
│ └── routes # Routes
├── TODO.md # TODO List
├── package.json
└── README.md
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
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 projectBy: 'name:hide, role:hide', // fields to hide or include in the results 6};
The projectBy
option can include multiple criteria (separated by a comma) but cannot include and exclude fields at the same time. Check out the following examples:
name:hide, role:hide
should workname:include, role:include
should workname:include, role:hide
will not workThe 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.
No security vulnerabilities found.