DEV Community


Posted on


How to successfully start with Nest.js and Postgres

In this tutorial will see how to install, configure postgres with Nest.js typeorm.


1. Let's install Postgres

Install postgres on the official website. I'll recommend installing it on the official website rather then using homebrew cause it could lead to some trouble later

2. Basic of Postgres

  • Start Postgres app and start server
    Image description

  • Open your terminal and add psql to your path.

export PATH="/Applications/$PATH"

Image description

Basic Command

To open psql terminal : psql postgres
Image description

  • List all Database with \l
    Image description``

  • Create a Database with CREATE DATABASE name;
    Image description

  • Connect to a Database with \c name
    Image description

  • Exit postgres with \q
    Image description


Setup Nest Project

npm i -g @nest/cli
nest new project-name

Create .env file for the config of our Database

Create a .env file containing the PORT, USERNAME, DATABASE NAME, URL ...


Configure App Module

Inside your app module add the .env config file :

import { ConfigModule } from '@nestjs/config';
ConfigModule.forRoot({ envFilePath: ['.env'] })

Configure and install TypeOrm

Install Typeorm postgres for Next :

npm install --save @nestjs/typeorm typeorm postgres

Then import our configuration inside the app.module :

import { TypeOrmModule } from '@nestjs/typeorm'
type: 'postgres',
host: 'process.env.POSTGRES_HOST,
port: parseInt(process.env.POSTGRES_PORT),
username: process.env.POSTGRES_USER,
database: process.env.POSTGRES_DB,
entities: [],
synchronize: true,
logging: true,
autoLoadEntities: true,

Little explanation
synchronize: true,
autoLoadEntities: true,

Allow schema to be automatically with Database.

Little explanation
logging: true

Log all the interaction with the Database

Create Entity

Create a user.entity.ts file inside an entities folder.

Image description
I won't go into detail about this code cause you can find good documentation on Typeorm website.

`import {
} from 'typeorm';

export class User {
id: number;

username: string;

email: string;

password: string;

nullable: true,
unique: true,
access_token: string;

created_at: Date;

Then inside your app.module add entities: [User]

Top comments (0)

12 APIs That You Will Love

Free and easy to use APIs for your next project, learning a new technology, or building a new feature.