Skip to content
the poor coder

nestjs pg heroku

Poor Man
Published
Reading time
4 min read
On this page

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:

Text

  $ nest new my-app

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

Text

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

Text

{
  "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:

Text

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

@Entity()
export class Post {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  title: string;

  @Column()
  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:

Text

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

@Controller('posts')
export class PostsController {
  constructor(
    @InjectRepository(Post)
    private readonly postRepository: Repository,
  ) {}

  @Get()
  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:

Text

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

@Module({
  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.

Text

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

Text

$ 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!

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC