A starter NodeJs project written in TypeScript for quickly building Express RESTful APIs using ORM, loggers, schema validator, authentication, unit test coverage, and much more.
Made with β€οΈ by Vincent Jean
The project is a concise and comprehensive TypeScript boilerplate specifically designed for rapid development of Express REST APIs. This is a boilerplate designed to streamline the creation of new API projects using Express. It provides a minimal set of dependencies that aid in project structuring and acceleration. The boilerplate is production-ready, although customization is recommended to align with specific project requirements.
The boilerplate includes various essential libraries and tools to support the development of your custom project. It leverages the power of Prisma ORM for seamless database operations, facilitates log management with Morgan and Winston to track HTTP request logs in real-time and store rotating log files with web visualization through the EJS engine.
Additionally, the boilerplate ensures robustness by offering comprehensive unit test coverage using Jest, data validation schemas with Zod, JWT middleware authentication, and Swagger documentation generation.
The project follows the MVC architecture and incorporates additional layers for enhanced support and customization. To ensure code quality and consistency, we have integrated ESLint and Prettier tools, enabling automated type-checking during TypeScript code development.
Rest assured, this repository is fully functional and ready for use.
To install the project, follow the steps below.
First, to clone the repository, you'll need Git installed on your computer. From your command line:
$ git clone https://github.com/vincent-queimado/express-prisma-ts-boilerplate.git
To run this application, you'll need Node.js (which comes with npm) installed on your computer. Make sure you install all the necessary dependencies to run the project from your command line:
$ cd express-prisma-ts-boilerplate
$ npm i
In the project folder you will find a .env.example
file, duplicate it and rename it to .env
only. The command below will copy the template environment variables file needed to initialize your project.
$ cp .env.example .env
After renaming the file, open it and change the desired variables ββaccording to your project:
#.env
APP_URL_HOST='localhost'
APP_URL_PORT='3344'
APP_URL_SSL='false'
...
Running locally in development
environment:
# development (watch mode)
$ npm run start:dev
When running locally, by default the API will be accessible at url http://localhost:3344 as illustrated below.
Running in a production
environment (the code will be transpiled in the build folder and executed):
# production mode
$ npm run start:prod
You will need to configure an SQL database supported by the Prisma ORM in order to perform the data storage. By default the boilerplate uses a demo connection to the PostgreSQL database, but it can be changed to another database supported by the Prisma ORM.
If you want to install another database, remove the Prisma folder, execute a new prisma initialization, follow the instructions and skip this section:
$ rm .\prisma
$ npx prisma init
If you want to continue with the PostgreSQL database but don't already have the software, download pgAdmin now or use a Hosting Cloud Service.
You will need to configure a SQL database supported by Prisma ORM for data storage.
Before running the project, it will be necessary to perform a migration through Prisma. In this way, the first tables of the project will be created. When executing the reset command, the ORM seed will be called, thus populating some tables:
Migration run command:
$ npm run migrate
Obs.: Initially, the project assumes that we will use the PostgreSQL database by default, but feel free to change the connection data to the database of your choice.
Name | Description |
---|---|
APP_URL_HOST | [String] It is the host the API will use. By default it is localhost. |
APP_URL_PORT | [String] It is the port the API will use. By default it is 3344. |
SSL_ALLOW | [String] Enable or disable SSL in the API. By default it is false. |
SSL_PRIVATE_KEY | [String] SSL private key file path. By default it is empty. |
SSL_CERTIFICATE | [String] SSL certificate file path. By default it is empty. |
API_PREFIX | [String] Api route prefix. By default it is api. |
API_JSON_LIMIT | [String] Limits request JSON body size. By default it is 5mb. |
API_EXT_URLENCODED | [String] The βextendedβ syntax allows for rich objects and arrays to be encoded into the URL-encoded format, allowing for a JSON-like experience with URL-encoded. By default it is false. |
CORS_ALLOW_ORIGIN | [String] CORS Allow Origin is a header that specifies which origins are allowed to access server resources. By default it is *. |
JWT_SECRET_USER | [String] The JWT secret is a key used for signing and verifying JSON Web Tokens (JWTs)I. By default it is mysecretuser. |
JWT_SECRET_DEVICE | [String] The JWT secret is a key used for signing and verifying JSON Web Tokens (JWTs)I. By default it is mysecretdevice. |
JWT_EXPIRED_IN | [String] JWT expiration is a time indicating when a JWT expires. By default it is 24h. |
BCRYPT_SALTROUNDS | [String] Bcrypt's salt rounds is the number of iterations used to hash a password, determining the computational cost and strength of the resulting hash. By default it is 10. |
RATE_LIMIT_MAX | [String] Max rate limiter is a mechanism that restricts the maximum number of requests allowed within a specified time period to prevent abuse or overload on a server or API. By default it is 100. |
RATE_LIMIT_WINDOW | [String] Rate limiter window is a time duration during which the rate limiting is enforced, limiting the number of requests allowed within that specific timeframe.. By default it is 15. |
DEBUG_HTTP_REQUEST | [String] Refers to a debugging technique or feature that enables detailed logging and analysis of HTTP requests, helping developers troubleshoot and understand the behavior of the requests being sent and received. By default it is true |
DEBUG_HTTP_CONNECTION | [String] Is a debugging feature that allows for detailed monitoring and analysis of the HTTP connection process, providing insights into the establishment, communication, and termination of HTTP connections, aiding in debugging network-related issues. By default it is false |
DATABASE_URL | [String] is a string that contains the necessary information (such as host, port, username, password, and database name) to establish a connection to a database. By default it is postgresql://johndoe:randompassword@localhost:5432/mydb?sslmode=require&schema=public. |
EMAIL_USER | [String] SSL private key file path. By default it is [email protected]. |
EMAIL_PASSWORD | [String] SSL private key file path. By default it is empty. |
EMAIL_SERVICE | [String] SSL private key file path. By default it is gmail. |
EMAIL_OAUTH_CLIENT_ID | [String] SSL private key file path. By default it is empty. |
EMAIL_OAUTH_CLIENT_SECRET | [String] SSL private key file path. By default it is empty. |
EMAIL_OAUTH_REFRESH_TOKEN | [String] SSL private key file path. By default it is empty. |
EMAIL_OAUTH_REDIRECT | [String] SSL private key file path. By default it is https://developers.google.com/oauthplayground. |
The boilerplate ships with several convenience commands (runnable via npm
):
npm run lint:check
: run code linting to check for syntax errorsnpm run lint:fix
: automatically fix lint problemsnpm run prettier:check
: checks that the code style is correctly formattednpm run prettier:format
: automatically fix prettier problemsnpm run test
: run functional tests with coveragenpm run test:watch
: run functional tests in watch modenpm run prisma:format
: check .prisma files formatnpm run prisma:migrate
: reads the data sources and data model definition to create a new migrationnpm run prisma:generate
: reads all above mentioned information to generate the data sourcenpm run prisma:generate:watch
: watch the Prisma schema and rerun after a changenpm run prisma:reset
: reset your database and apply all migrations, all data will be lostnpm run prisma:seed
: seed the databasenpm run commit
: help you follow conventional commits flow
Boilerplate structure summary:
build\ # Transpiled TypeScript code to Javasccript
coverage\ # Unit test reports
docs\ # Documentation / Postman collection / Readme assets
logs\ # Log files (generate with Winston packages)
node_modules\ # NodeJS packages
prisma\ # Prisma schema and client connection / Migrations and seed
|--migrations\ # Database migration
|--seed\ # Database seed
public\ # Public ressources
src\ # Sources
|--config\ # Environment variables and configuration related things
|--app\ # App configuration file
|--database\ # Database configuration file
|--email\ # Email configuration file
|--constants\ # Constants
|--controllers\ # Controllers
|--plataform # Plataform business logic
|--dao\ # Responsible for retrieving and sending data to the database
|--database\ # Database connection
|--functions\ # Functions
|--middlewares\ # Middlewares (JWT auth, data validation schema, Morgan, and other middlewares)
|--models\ # Models
|--routes\ # Custom Routes
|--schemas\ # Schema validation
|--server\ # Http server using the Express framework
|--services\ # Services
|--utils\ # Utility handler, logger, mailer, etc..
|--views\ # Views (basic views renderized by EJS engine)
|--app.js # Entry point
tests\ # Unit test coverage with Jest
Some examples of ready-made endpoints are available. When importing a Postman collection to the project folder docs
>postman
, an web documentation will be automatically generated via Swagger.
Rota | HTTP (Verbs) | Description |
---|---|---|
/api/client/info | GET | Api informations |
/api/client/logs | GET | Api logs |
/api/client/docs | GET | Swagger doc (not allow in prod) |
/api/client/auth/login | POST | Login |
/api/client/auth/logout | GET | Logout |
/api/client/auth/register | POST | Register |
/api/client/auth/register/confirmation | GET | Register confirmation |
/api/client/auth/forgotpassword/request | POST | Forgot password request |
/api/client/auth/forgotpassword/reset | POST | Forgot password reset |
/api/client/user/me | GET | Show me |
/api/client/user/me | PATCH | Update me |
/api/client/user/me | DELETE | Delete me |
/api/admin/users | GET | Show all users |
The automatically generated documentation will be accessible on the web at url http://localhost:3344/api/docs.
Implementation of error logs and information related to the API stored in a rotating file with standard time and size. Logs are available via web interface in development environments at url http://localhost:3344/api/logs.
Download and install the pgAdmin tool for PostgreSQL database management.
Run pgAdmin
. Right-click on the item Servers
, select Create
-> Server
and provide the connection to your PostgreSQL instance configured in the pgAdmin installation step. On the connection tab, make sure you have filled in the host as localhost as well as the access credentials. Click Save
afterwards.
Run pgAdmin
. Right-click on the item Servers
, select Create
-> Server
and provide the connection to your PostgreSQL instance configured in the pgAdmin installation step. On the connection tab, make sure you have filled in the host as localhost as well as the access credentials. Click Save
afterwards.
Reports the URL based on the credentials and database information in the DATABASE_URL
variable located in the .env
file. Example:
#.env
...
# DATABASE
DATABASE_URL="postgresql://johndoe:randompassword@localhost:5432/mydb?sslmode=require&schema=public"
...
ElephantSQL is a free tier hosting cloud service for the PostgreSQL database, bypassing all those infrastructure headaches (https://api.elephantsql.com/).
Create a free instance (Tiny Turtle plan) and copy the URL in the DATABASE_URL
variable of the .env
file. The free version is limited to 20MB.