Setup NestJs Server on Heroku
A progressive Node.js framework for building efficient, reliable and scalable server-side applications.
2 min readJun 21, 2019
Create new NestJS projet
npm i -g @nestjs/cli
nest new project-name
npm run start
// start at http://localhost:3000/
Add a new Controller
// add in src/cards.controller.ts
import {Controller, Get, Req} from '@nestjs/common';
import {Request} from 'express';@Controller('cards')
export class CardsController {
@Get('/')
getIndex(@Req() request: Request): string {
return `my first controller: ${request.method}`;
}
}// update app.module.ts
// restart node, default port is 3000
// Visit http://localhost:3000/cards/
Deploy to Heroku (Run time Build)
Update main.ts
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.enableCors(); // protection
await app.listen(process.env.PORT || '80');
}
bootstrap();
Create Procfile file
web: npm run start:prod
// this enable to start without using ts-node
// this will run prestart:prod automatically
Update Node Config
heroku config:set NPM_CONFIG_PRODUCTION=false
heroku config:set NODE_ENV=production
// this allow us to build in heroku
Deploy to Heroku via git
heroku login
git init // init githeroku create // create app on heroku
// or
heroku git:remote -a heroku-testinggit add . // add files
git commit -m "Initial commit" // commit the files
git push heroku master // deploy
heroku logs -n 200 // view logs
Deploy to Heroku (With source code)
This allow a slept Heroku App to wake up faster.
Update .gitIgnore
# /dist
Update package.json, add scripts
“start:dist”: “node dist/main.js”,
Update/Create Procfile
web: npm run start:dist
Build and commit files
npm run build
git add .
git commit -m "auto"
git push heroku master