nestjs pg heroku

NestJS with Postgres on Heroku

If you're looking to develop a backend application with Node.js, NestJS is a popular framework that makes it easier to build scalable and maintainable applications. And if you're planning to use a relational database like Postgres, Heroku is a great cloud platform for hosting your application.

Setting up a Postgres database on Heroku

Before we get started with NestJS, let's first set up a Postgres database on Heroku.

  • Log in to your Heroku account and create a new app.
  • Click on the "Resources" tab and search for "Heroku Postgres".
  • Select the "Hobby Dev - Free" plan and click "Provision."
  • Go to the "Settings" tab and click on "Reveal Config Vars".
  • Add a new variable called "DATABASE_URL" and copy the value.

Now we're ready to start building our NestJS application!

Setting up NestJS with Postgres

The first step is to create a new NestJS application. You can do this using the NestJS CLI:

  $ nest new my-app

Next, we need to install the dependencies for working with Postgres:

  $ npm install --save @nestjs/typeorm typeorm pg

The @nestjs/typeorm package provides integration between NestJS and TypeORM, which is a popular ORM for working with databases. The typeorm package provides the core functionality for working with databases, and pg is the Postgres driver.

Next, we need to configure TypeORM to connect to our Heroku Postgres database. We can do this by creating a new ormconfig.json file in the root of our project:

  "type": "postgres",
  "url": "DATABASE_URL",
  "entities": ["dist/**/*.entity{.ts,.js}"],
  "synchronize": true

The "type" field tells TypeORM that we're using Postgres, and the "url" field tells it to use the value of the DATABASE_URL environment variable that we set up earlier. The "entities" field tells TypeORM where to find our entity classes (more on those in a bit), and the "synchronize" field tells TypeORM to automatically create database tables based on our entity classes.

Finally, we need to create an entity class that represents a table in our database. For example, if we're building a blog application, we might create a Post entity:

import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';

export class Post {
  id: number;

  title: string;

  body: string;

  @Column({ default: false })
  published: boolean;

The @Entity() decorator tells TypeORM that this class represents a table in our database. The @PrimaryGeneratedColumn() decorator tells TypeORM to generate a unique ID for each row in the table. The @Column() decorator tells TypeORM that this property should be a column in the table. We can also specify default values for columns, as we did for the published column.

Now we're ready to start using our database in our NestJS application. For example, we might create a new PostsController that retrieves all posts from the database:

import { Controller, Get } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Post } from './post.entity';

export class PostsController {
    private readonly postRepository: Repository,
  ) {}

  async findAll(): Promise {
    return this.postRepository.find();

The @InjectRepository(Post) decorator tells NestJS to inject a repository instance for the Post entity. We can then use this repository to perform database operations, such as retrieving all posts using the find() method.

Finally, we need to configure our NestJS application to use TypeORM. We can do this by updating the app.module.ts file:

import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { PostsController } from './posts.controller';
import { Post } from './post.entity';

  imports: [TypeOrmModule.forRoot(), TypeOrmModule.forFeature([Post])],
  controllers: [PostsController],
export class AppModule {}

The TypeOrmModule.forRoot() method tells NestJS to use the ormconfig.json file that we created earlier to configure TypeORM. The TypeOrmModule.forFeature([Post]) method tells NestJS to include the Post entity in the application.

And that's it! With these steps, we've set up a NestJS application with a Postgres database hosted on Heroku. Of course, there's a lot more you can do with NestJS and TypeORM, such as adding validation, pagination, or authentication. But this should give you a good starting point.

$ nest generate module posts
$ nest generate controller posts
$ nest generate service posts
$ npm install --save @nestjs/typeorm typeorm pg
$ npm install --save-dev @types/pg @types/typeorm

If you want to test your app locally, you can use the Heroku CLI to download your database credentials:

$ heroku pg:credentials:url DATABASE --app your-app-name

This will give you a URL that you can use in your ormconfig.json file instead of the DATABASE_URL environment variable.

Happy coding!

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]