Research
Security News
Quasar RAT Disguised as an npm Package for Detecting Vulnerabilities in Ethereum Smart Contracts
Socket researchers uncover a malicious npm package posing as a tool for detecting vulnerabilities in Etherium smart contracts.
node-express-typeorm-app
Advanced tools
Create a Node.js (typescript) app for building production-ready RESTful APIs using Express, by running one command
A boilerplate/starter project for quickly building RESTful APIs using Node.js, Express, and typeorm.
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, custom logging, etc. For more details, check the features list below.
Setup database settings inside ormconfig.json
file
To create a project, simply run:
npx create-node-express-typeorm-app <project-name>
Or
npm init node-express-typeorm-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/OsamaShahid/node-express-typeorm-boilerplate.git
cd node-express-typeorm-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:
npm run start:dev
Running in production:
npm run start
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)
|--middlewares\ # Custom express middlewares
|--models\ # typeorm entity models (data layer)
|--routes\ # Routes
|--manager\ # Business logic (service layer)
|--utils\ # Utility classes and functions
|--helper\validations\ # Request data validation schemas
|--app.ts # Express app
|--index.ts # App entry point
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
The app has a custom error handling mechanism.
Controllers should try to catch the errors and log them using custom logger and forward them to the api response.
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/helper/console.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 '<path to src>/helper';
logger.error('message'); // level 0
logger.important('message'); // level 0
logger.mute('message'); // level: 0
logger.debug('message'); // level 0
logger.warn('message'); // level 1
logger.success('message'); // level 2
logger.info('message'); // level 3
Contributions are more than welcome! Please check out the contributing guide.
FAQs
Create a Node.js (typescript) app for building production-ready RESTful APIs using Express, by running one command
The npm package node-express-typeorm-app receives a total of 1 weekly downloads. As such, node-express-typeorm-app popularity was classified as not popular.
We found that node-express-typeorm-app demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Research
Security News
Socket researchers uncover a malicious npm package posing as a tool for detecting vulnerabilities in Etherium smart contracts.
Security News
Research
A supply chain attack on Rspack's npm packages injected cryptomining malware, potentially impacting thousands of developers.
Research
Security News
Socket researchers discovered a malware campaign on npm delivering the Skuld infostealer via typosquatted packages, exposing sensitive data.