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
Then go to the directory which you want to create the project and type
nest new project-name
Open the project in your favorite code editor
Type in below lines to terminal to generate modules,collections and services.
nest generate module users
nest generate controller users
nest generate service users
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.
Search for Heroku Postgres and select it.
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
And then install nestjs config dependency.
npm i --save @nestjs/config
npm install --save @nestjs/typeorm typeorm pg
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 {}
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;
}
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 {}
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;
}
}
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);
}
}
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
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();
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.
(URL should be your own app's url!)
Now that we add the user. Let's see if we can get it from database.
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)
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.
And great article by the way
any github link please ?
Thanks :)