Skip to content

ividrine/express-api-sql

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

codecov

Node Express API Boilerplate

A starter project for quickly building RESTful APIs using Node.js, Express, and Prisma.

Table of Contents
  1. About The Project
  2. Getting Started
  3. Features
  4. Commands
  5. Environment Variables
  6. Project Structure
  7. API Documentation
  8. Error Handling
  9. Validation
  10. Authentication
  11. Authorization
  12. Logging
  13. Linting

About The Project

This project is a fork of RESTful API Node Server Boilerplate that adds type safety and works for relational databases.

Built With

Node.js TypeScript Express Prisma PostgreSQL JWT Zod Winston Vitest Scalar ESLint Prettier Husky Docker pnpm

(back to top)

Getting Started

Prerequisites

  • Node
  • Docker - for local external app dependencies/tools (Postgres, Valkey, PGAdmin)
  • Git Bash (if on windows)

Quick Start

  1. Run npx create-express-sql-app yourAppName or npm init express-sql-app yourAppName to initialize a new project.
  2. cd yourAppName and npm run dev to start the app

Manual Installation

For manual installations, follow these steps

  1. Clone the repo
git clone --depth 1 https://github.com/ividrine/express-api-sql.git
cd express-api-sql
npx rimraf ./.git
  1. Install the dependencies:
pnpm install
  1. Set the environment variables:
cp .env.example .env

# open .env and modify the environment variables (if needed)

(back to top)

Features

(back to top)

Commands

These are the npm scripts defined in package.json

"build": "rm -rf ./dist/ && prisma generate && tsc",
"lint": "eslint",
"prod": "sh ./scripts/run-prod.sh",
"dev": "sh ./scripts/run-dev.sh",
"test": "sh ./scripts/run-tests.sh",
"envup": "docker-compose up --build -d",
"envdown": "docker-compose down",
"prepare": "husky"

build

Removes the dist directory, generates prisma client and compiles typescript.

lint

Runs eslint.

prod

Generates prisma client, sets NODE_ENV to prod and runs compiled js.

dev

Starts external app dependencies with docker-compose, runs prisma migration / seeds database if needed and starts app in watch mode.

test

Runs docker-compose unless passed "CI" as the first argument, in which case it skips this step. Can pass any number of vitest options to this command. Ex. npm run test --ui --coverage or npm run test CI --coverage

envup

Starts external app dependencies with docker-compose.

envdown

Tears down external app dependencies. You can pass arguments to underlying docker-compose command like this pnpm envdown -- -v or npm run envdown -- -v to also remove volumes.

prepare

Runs husky to install/setup git hooks

(back to top)

Environment Variables

This project uses .env files to load environment variables into node's process.env object for local development. They are git ignored to avoid checking secrets and other sensitive data into source control. See here for more information about environment variables in node.

The environment variables can be found and modified in the .env file. They come with these default values

# App
NODE_ENV=development
PORT=3000

# Database
DATABASE_URL=postgresql://postgres:postgres@localhost:5432/appdb

# Valkey
VALKEY_URL=localhost:6379

# JWT
JWT_SECRET=thisisasamplesecret
JWT_ACCESS_EXPIRATION_MINUTES=30
JWT_REFRESH_EXPIRATION_DAYS=30
JWT_RESET_PASSWORD_EXPIRATION_MINUTES=10
JWT_VERIFY_EMAIL_EXPIRATION_MINUTES=10
JWT_ISSUER=nodeapp
JWT_AUDIENCE=nodeapp

# SMTP - 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 protected]

(back to top)

Project Structure

src\
 |--config\         # Environment variables and configuration related things
 |--constants\      # App constants
 |--controllers\    # Route controllers (controller layer)
 |--docs\           # Swagger files
 |--lib\            # Db clients / connections / integrations
 |--middlewares\    # Custom express middlewares
 |--routes\         # Routes
 |--services\       # Business logic (service layer)
 |--types\          # Typescript types/interfaces
 |--utils\          # Utility classes and functions
 |--validations\    # Request data validation schemas
 |--app.js          # Express app
 |--index.js        # App entry point

(back to top)

API Documentation

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 openapi definitions written as comments in the route files.

API Endpoints

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

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

(back to top)

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.

import catchAsync from "../utils/catchAsync.js";

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:

import httpStatus from "http-status";
import ApiError from "../utils/ApiError.js";
import prisma from "../lib/prisma/index.js";

const getUser = async (userId) => {
  const user = await prisma.user.findUnique({ where: { id: userId } });
  if (!user) {
    throw new ApiError(httpStatus.NOT_FOUND, "User not found");
  }
};

(back to top)

Validation

Request data is validated using Zod. Check the documentation for more details on how to write Zod 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.

import express from "express";
import validate from "../../middlewares/validate.js";
import userValidation from "../../validations/user.validation.js";
import userController from "../../controllers/user.controller.js";

const router = express.Router();

router.post(
  "/users",
  validate(userValidation.createUser),
  userController.createUser
);

(back to top)

Authentication

To require authentication for certain routes, you can use the authorize middleware.

import express from "express";
import authorize from "../../middlewares/auth.js";
import userController from "../../controllers/user.controller.js";

const router = express.Router();

router.post("/users", authorize(), 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.

(back to top)

Authorization

The authorize middleware can also be used to require certain permissions to access a route.

import express from "express";
import authorize from "../../middlewares/auth.js";
import userController from "../../controllers/user.controller.js";
import { CREATE_USERS } from "../../constants/permission.constants.js";

const router = express.Router();

router.post("/users", authorize(CREATE_USERS), userController.createUser);

In the example above, an authenticated user can access this route only if that user has the CREATE_USERS permission.

The permissions are role-based. You can view the permissions/rights of each role in the src/constants/role.constants.ts file.

If the user making the request does not have the required permissions to access this route, a Forbidden (403) error is thrown.

(back to top)

Logging

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):

import logger from "<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 to actually read them from the console and store them in log files.\

Note: API request information (request url, response code, timestamp, etc.) are also automatically logged (using morgan).

(back to top)

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 eslint.config.ts file. To modify the Prettier configuration, update the .prettierrc file.

To prevent a certain file or directory from being linted, add to the ignores array in eslint.config.ts and update .prettierignore.

To maintain a consistent coding style across different IDEs, the project contains .editorconfig

(back to top)

Contributing

Contributions are more than welcome! Please check out the contributing guide.

Inspirations

License

MIT

(back to top)

About

A starter project for quickly building RESTful APIs using Node.js, Express, and Prisma.

Topics

Resources

License

Code of conduct

Contributing

Stars

Watchers

Forks

Contributors 2

  •  
  •