DEV Community

Cover image for Connecting Heroku Postgres with NestJS Backend
Ömer Berkan Çalık
Ömer Berkan Çalık

Posted on

Connecting Heroku Postgres with NestJS Backend

Hi all! 👋

This is my first article on here. In this article I'll show you how you can connect a postgres database to your backend api, and how to deploy it on heroku. This is not a tutorial for NestJS so i assume that you know at least the basic.

If you found this article helpful make sure you follow me on Twitter. I am planning to share resources and tips on my twitter.

First we need to install Nestjs.

npm i -g @nestjs/cli
Enter fullscreen mode Exit fullscreen mode

Then go to the directory which you want to create the project and type

nest new project-name
Enter fullscreen mode Exit fullscreen mode

Open the project in your favorite code editor
image

Type in below lines to terminal to generate modules,collections and services.

nest generate module users
nest generate controller users
nest generate service users
Enter fullscreen mode Exit fullscreen mode

After that nest will create the necessary files for us.

Go to Heroku and create a new app.After you created the app go to overview tab and click configure add-ons.
image

Search for Heroku Postgres and select it.
image

After you add the database click on it. You will be redirected to database dashboard. Go to setting tab and copy the URI.

Create a .env file in the root directory and type

DATABASE_URL=your_database_url
Enter fullscreen mode Exit fullscreen mode

And then install nestjs config dependency.

npm i --save @nestjs/config
npm install --save @nestjs/typeorm typeorm pg
Enter fullscreen mode Exit fullscreen mode

Then go to your app.module.ts file and add the following lines. Your app.module.ts file should look like this.

import { ConfigModule } from '@nestjs/config';

import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { UsersModule } from './users/users.module';
import { TypeOrmModule } from '@nestjs/typeorm';

@Module({
  imports: [
    UsersModule,
    ConfigModule.forRoot(),
    TypeOrmModule.forRoot({
      url: process.env.DATABASE_URL,
      type: 'postgres',
      ssl: {
        rejectUnauthorized: false,
      },
      entities: ['dist/**/*.entity{.ts,.js}'],
      synchronize: true, // This for development
      autoLoadEntities: true,
    }),
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}
Enter fullscreen mode Exit fullscreen mode

Now we need to create a User entity and inject it to our service.
Create a file called "user.entity.ts" in the users folder.
It should look like this.

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

@Entity('users')
export class User{
  @PrimaryGeneratedColumn()
  id?: number;

  @Column()
  username: string;

  @Column()
  password: string;
}
Enter fullscreen mode Exit fullscreen mode

Now go to "users.module.ts" file and add the following line to your "@Module" decorator so it should look like below.

import { User } from './user.entity';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Module } from '@nestjs/common';
import { UsersController } from './users.controller';
import { UsersService } from './users.service';

@Module({
  imports: [TypeOrmModule.forFeature([User])],
  controllers: [UsersController],
  providers: [UsersService],
})
export class UsersModule {}
Enter fullscreen mode Exit fullscreen mode

And then go to "users.service.ts" file and edit it like below.

import { User } from './user.entity';
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';

@Injectable()
export class UsersService {
  constructor(
    @InjectRepository(User)
    private usersRepository: Repository<User>,
  ) {}

  getUsers(): Promise<User[]> {
    return this.usersRepository.find();
  }

  addUser(user): Promise<User> {
    this.usersRepository.insert(user);
    return user;
  }
}
Enter fullscreen mode Exit fullscreen mode

And finally go to "users.controller.ts" file and paste the below code.

import { UsersService } from './users.service';
import { Body, Controller, Get, Post } from '@nestjs/common';

type User = {
  id?: number;
  username: string;
  password: string;
};

@Controller('users')
export class UsersController {
  constructor(private readonly userService: UsersService) {}

  @Get()
  getUsers() {
    return this.userService.getUsers();
  }

  @Post()
  addUser(@Body() user: User) {
    return this.userService.addUser(user);
  }
}
Enter fullscreen mode Exit fullscreen mode

We created our really simple API. Now we need to make some changes for deployment.

First create a "Procfile" without extensions in the root folder. And paste the below code inside it.

web: npm run start:prod
Enter fullscreen mode Exit fullscreen mode

image

And finally go to your "main.ts" file inside the src folder and edit it like below.

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  const PORT = process.env.PORT || 5000;
  await app.listen(PORT);
}
bootstrap();
Enter fullscreen mode Exit fullscreen mode

Now we are ready to deploy our api on Heroku! First go ahead and create a github repository and push your code to it(Dont forget to add your ".env" file to gitignore). Then go to your already created app and click deploy tab. Click GitHub and search for your repository and select it. Enable Automatic Deploys if you want it to deploy your code whenever you push to your main branch. And finally click deploy below.

Now lets test our api on Insomnia.

image
(URL should be your own app's url!)

Now that we add the user. Let's see if we can get it from database.

image

As you can see we successfully get our user. After that you can try to implement deleting or updating users.

Thanks for the reading. I hope you found it useful. If you have any questions feel free to ask. Bye 👋

Top comments (4)

Collapse
 
datnguyen2001 profile image
dat nguyen

After struggling for hours tryin' to figure out how to connect Nest to Heroku Postgres, this article has saved my day. Thank you so much.

Collapse
 
edgaremmanuel profile image
DevByJESUS

And great article by the way

Collapse
 
edgaremmanuel profile image
DevByJESUS

any github link please ?

Collapse
 
emreaka profile image
Emre AKA

Thanks :)