├── .env ├── .eslintrc.js ├── .gitignore ├── .prettierrc ├── Procfile ├── README.md ├── images └── estrutura-main-ts.png ├── nest-cli.json ├── package-lock.json ├── package.json ├── prisma ├── schema.prisma └── sqlite.db ├── src ├── app.controller.spec.ts ├── app.controller.ts ├── app.module.ts ├── app.service.ts ├── main.ts └── users │ ├── dto │ ├── create-user.dto.ts │ └── update-user.dto.ts │ ├── entities │ └── user.entity.ts │ ├── users.controller.spec.ts │ ├── users.controller.ts │ ├── users.module.ts │ ├── users.service.spec.ts │ └── users.service.ts ├── test ├── app.e2e-spec.ts └── jest-e2e.json ├── tsconfig.build.json └── tsconfig.json /.env: -------------------------------------------------------------------------------- 1 | DATABASE_URL="file:./sqlite.db" 2 | -------------------------------------------------------------------------------- /.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | parser: '@typescript-eslint/parser', 3 | parserOptions: { 4 | project: 'tsconfig.json', 5 | sourceType: 'module', 6 | }, 7 | plugins: ['@typescript-eslint/eslint-plugin'], 8 | extends: [ 9 | 'plugin:@typescript-eslint/recommended', 10 | 'plugin:prettier/recommended', 11 | ], 12 | root: true, 13 | env: { 14 | node: true, 15 | jest: true, 16 | }, 17 | ignorePatterns: ['.eslintrc.js'], 18 | rules: { 19 | '@typescript-eslint/interface-name-prefix': 'off', 20 | '@typescript-eslint/explicit-function-return-type': 'off', 21 | '@typescript-eslint/explicit-module-boundary-types': 'off', 22 | '@typescript-eslint/no-explicit-any': 'off', 23 | }, 24 | }; 25 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # compiled output 2 | /dist 3 | /node_modules 4 | 5 | # Logs 6 | logs 7 | *.log 8 | npm-debug.log* 9 | pnpm-debug.log* 10 | yarn-debug.log* 11 | yarn-error.log* 12 | lerna-debug.log* 13 | 14 | # OS 15 | .DS_Store 16 | 17 | # Tests 18 | /coverage 19 | /.nyc_output 20 | 21 | # IDEs and editors 22 | /.idea 23 | .project 24 | .classpath 25 | .c9/ 26 | *.launch 27 | .settings/ 28 | *.sublime-workspace 29 | 30 | # IDE - VSCode 31 | .vscode/* 32 | !.vscode/settings.json 33 | !.vscode/tasks.json 34 | !.vscode/launch.json 35 | !.vscode/extensions.json -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "singleQuote": true, 3 | "trailingComma": "all" 4 | } -------------------------------------------------------------------------------- /Procfile: -------------------------------------------------------------------------------- 1 | web: npm run start:prod 2 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # NestJS - Deploy Heroku 2 | 3 | Fazer o Deploy no Heroku de uma aplicação NestJS é relativamente simples, mas com alguns pequenos detalhes que são bem importantes. 4 | 5 | Dessa vez, faremos o deploy de uma aplicação NestJS conectada a um banco de dados SQLite através do ORM Prisma. 6 | 7 | Alterar o tipo de banco de dados e a URL para qualquer outro provedor será bem fácil através das variáveis de ambiente, então chega junto pra mais um conteúdo massa 😃 8 | 9 | ## Configuração 10 | 11 | ### Configurando a porta 12 | 13 | Abra o arquivo `main.ts` e certifique-se de que a porta está devidamente configurada para acessar a variável de ambiente `PORT` que o Heroku fornece: 14 | 15 | `src/main.ts` 16 | 17 | ```typescript 18 | import { NestFactory } from '@nestjs/core'; 19 | import { AppModule } from './app.module'; 20 | 21 | async function bootstrap() { 22 | const app = await NestFactory.create(AppModule); 23 | 24 | await app.listen(process.env.PORT || 3000); 25 | } 26 | 27 | bootstrap(); 28 | ``` 29 | 30 | ### Arquivo `Procfile` 31 | 32 | Normalmente o Heroku utiliza o comando `npm start` para rodar a aplicação. Por padrão, o Nest executa o comando `nest start` quando executamos esse script, no entanto, para rodar a aplicação em produção, é recomendado executar os arquivos JavaScript da pasta `dist` diretamente. 33 | 34 | Para isso, precisamos criar um arquivo na raiz do projeto chamado `Procfile`, com `P` maiúsculo e sem nenhuma extensão de arquivo. 35 | 36 | `Procfile` 37 | 38 | ``` 39 | web: npm run start:prod 40 | ``` 41 | 42 | Dessa forma, o Heroku sempre executará nossa aplicação através do comando `npm run start:prod`. 43 | 44 | ### Script `start:prod` 45 | 46 | Por padrão, o Nest já vem com esse comando, que por baixa executa `node dist/main`. 47 | 48 | `package.json` 49 | 50 | ```json 51 | { 52 | "name": "nestjs-deploy-heroku", 53 | // ... 54 | "scripts": { 55 | // ... 56 | "start:prod": "node dist/main" 57 | } 58 | } 59 | ``` 60 | 61 | #### Atenção para alguns casos: `dist/main.ts` vs `dist/src/main.ts` 62 | 63 | Em alguns casos, quando possuímos arquivos JavaScript ou TypeScript fora da pasta `src`, a estrutura da pasta `dist` mudará. 64 | 65 | Certifique-se de que o arquivo `main.js`, que foi compilado a partir do arquivo `main.ts` está no caminho correto, indicado no script `start:prod`. 66 | 67 | - Opção 1 (mais comum): `dist/main.js`; 68 | - Opção 2 (quando tem arquivos JS ou TS fora da `src`): `dist/src/main.js`; 69 | - Opção 3 (mais incomum): outra localização, dependendo de onde estiver seu arquivo `main.ts`. 70 | 71 | > Se o seu arquivo `main.js` estiver em uma localização diferente da que o Nest usa como padrão, certifique-se de atualizar no script `start:prod`. 72 | 73 | ##### Alguns exemplos de estrutura da pasta `dist` 74 | 75 | ![Localização do arquivo main.js](images/estrutura-main-ts.png) 76 | 77 | ### Garantindo que a pasta `dist` está sempre atualizada 78 | 79 | É importante garantir que o Heroku fará o build da aplicação (para manter a pasta `dist` sempre atualizada), portanto, devemos adicionar o script `heroku-postbuild` no arquivo `package.json`, informando para o Heroku sempre executar alguns comandos assim que passar da sua etapa de `build`. 80 | 81 | `package.json` 82 | 83 | ```json 84 | { 85 | "name": "nestjs-deploy-heroku", 86 | // ... 87 | "scripts": { 88 | // ... 89 | "heroku-postbuild": "NODE_ENV=dev npm install --omit --no-shrinkwrap && npm run build" 90 | } 91 | } 92 | ``` 93 | 94 | ## Realizando o deploy 95 | 96 | Agora que finalizamos a etapa de configuração, basta subir o projeto para o Heroku (através do GitHub ou da própria Heroku CLI) e tudo estará funcionando normalmente. 97 | 98 | > **ATENÇÃO!** 99 | > 100 | > Caso a sua aplicação não funcione, pode ser que tenha algum erro adicional, seja no build ou na execução. ☹ 101 | > 102 | > 1️⃣ Se o erro for em build, aparecerá a mensagem `Build failed` e você poderá visualizar os erros direto pelo site do Heroku. 103 | > 104 | > 2️⃣ Se o erro for na execução e aparecer a mensagem `Application error` ao tentar acessar a URL gerada para o seu app, certifique-se de configurar a Heroku CLI e executar o comando `heroku logs`, para conseguir verificar qual foi o problema e tentar corrigir. 105 | > 106 | > 🛠 **Saiba como configurar a Heroku CLI no vídeo:** https://www.youtube.com/watch?v=n4wFqLm98x0 107 | 108 | ## Conclusão 109 | 110 | Curtiu? Ficou fácil fazer o deploy de uma aplicação NestJS no Heroku, não?! 111 | 112 | Agora não tem mais desculpa pra ter a sua aplicação rodando na nuvem, em um serviço completamente gratuito! 113 | 114 | Um beijo pra vcs. 🧡 115 | -------------------------------------------------------------------------------- /images/estrutura-main-ts.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FabricaDeSinapse/nestjs-deploy-heroku/870d782ceb691efeebfeef5e5922c4cdec03357e/images/estrutura-main-ts.png -------------------------------------------------------------------------------- /nest-cli.json: -------------------------------------------------------------------------------- 1 | { 2 | "collection": "@nestjs/schematics", 3 | "sourceRoot": "src" 4 | } -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "nestjs-deploy-heroku", 3 | "version": "0.0.1", 4 | "description": "", 5 | "author": "", 6 | "private": true, 7 | "license": "UNLICENSED", 8 | "scripts": { 9 | "prebuild": "rimraf dist", 10 | "build": "nest build", 11 | "format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"", 12 | "start": "nest start", 13 | "start:dev": "nest start --watch", 14 | "start:debug": "nest start --debug --watch", 15 | "start:prod": "node dist/main", 16 | "lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix", 17 | "test": "jest", 18 | "test:watch": "jest --watch", 19 | "test:cov": "jest --coverage", 20 | "test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand", 21 | "test:e2e": "jest --config ./test/jest-e2e.json", 22 | "heroku-postbuild": "NODE_ENV=dev npm install --omit --no-shrinkwrap && npm run build" 23 | }, 24 | "dependencies": { 25 | "@nestjs/common": "^8.0.0", 26 | "@nestjs/core": "^8.0.0", 27 | "@nestjs/mapped-types": "^1.0.0", 28 | "@nestjs/platform-express": "^8.0.0", 29 | "@prisma/client": "^3.3.0", 30 | "reflect-metadata": "^0.1.13", 31 | "rimraf": "^3.0.2", 32 | "rxjs": "^7.2.0" 33 | }, 34 | "devDependencies": { 35 | "@nestjs/cli": "^8.0.0", 36 | "@nestjs/schematics": "^8.0.0", 37 | "@nestjs/testing": "^8.0.0", 38 | "@types/express": "^4.17.13", 39 | "@types/jest": "^27.0.1", 40 | "@types/node": "^16.0.0", 41 | "@types/supertest": "^2.0.11", 42 | "@typescript-eslint/eslint-plugin": "^4.28.2", 43 | "@typescript-eslint/parser": "^4.28.2", 44 | "eslint": "^7.30.0", 45 | "eslint-config-prettier": "^8.3.0", 46 | "eslint-plugin-prettier": "^3.4.0", 47 | "jest": "^27.0.6", 48 | "prettier": "^2.3.2", 49 | "prisma": "^3.3.0", 50 | "supertest": "^6.1.3", 51 | "ts-jest": "^27.0.3", 52 | "ts-loader": "^9.2.3", 53 | "ts-node": "^10.0.0", 54 | "tsconfig-paths": "^3.10.1", 55 | "typescript": "^4.3.5" 56 | }, 57 | "jest": { 58 | "moduleFileExtensions": [ 59 | "js", 60 | "json", 61 | "ts" 62 | ], 63 | "rootDir": "src", 64 | "testRegex": ".*\\.spec\\.ts$", 65 | "transform": { 66 | "^.+\\.(t|j)s$": "ts-jest" 67 | }, 68 | "collectCoverageFrom": [ 69 | "**/*.(t|j)s" 70 | ], 71 | "coverageDirectory": "../coverage", 72 | "testEnvironment": "node" 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /prisma/schema.prisma: -------------------------------------------------------------------------------- 1 | // This is your Prisma schema file, 2 | // learn more about it in the docs: https://pris.ly/d/prisma-schema 3 | 4 | generator client { 5 | provider = "prisma-client-js" 6 | } 7 | 8 | datasource db { 9 | provider = "sqlite" 10 | url = env("DATABASE_URL") 11 | } 12 | 13 | model User { 14 | id Int @id @default(autoincrement()) 15 | name String 16 | email String @unique 17 | password String 18 | } 19 | -------------------------------------------------------------------------------- /prisma/sqlite.db: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FabricaDeSinapse/nestjs-deploy-heroku/870d782ceb691efeebfeef5e5922c4cdec03357e/prisma/sqlite.db -------------------------------------------------------------------------------- /src/app.controller.spec.ts: -------------------------------------------------------------------------------- 1 | import { Test, TestingModule } from '@nestjs/testing'; 2 | import { AppController } from './app.controller'; 3 | import { AppService } from './app.service'; 4 | 5 | describe('AppController', () => { 6 | let appController: AppController; 7 | 8 | beforeEach(async () => { 9 | const app: TestingModule = await Test.createTestingModule({ 10 | controllers: [AppController], 11 | providers: [AppService], 12 | }).compile(); 13 | 14 | appController = app.get(AppController); 15 | }); 16 | 17 | describe('root', () => { 18 | it('should return "Hello World!"', () => { 19 | expect(appController.getHello()).toBe('Hello World!'); 20 | }); 21 | }); 22 | }); 23 | -------------------------------------------------------------------------------- /src/app.controller.ts: -------------------------------------------------------------------------------- 1 | import { Controller, Get } from '@nestjs/common'; 2 | import { AppService } from './app.service'; 3 | 4 | @Controller() 5 | export class AppController { 6 | constructor(private readonly appService: AppService) {} 7 | 8 | @Get() 9 | getHello(): string { 10 | return this.appService.getHello(); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/app.module.ts: -------------------------------------------------------------------------------- 1 | import { Module } from '@nestjs/common'; 2 | import { AppController } from './app.controller'; 3 | import { AppService } from './app.service'; 4 | import { UsersModule } from './users/users.module'; 5 | 6 | @Module({ 7 | imports: [UsersModule], 8 | controllers: [AppController], 9 | providers: [AppService], 10 | }) 11 | export class AppModule {} 12 | -------------------------------------------------------------------------------- /src/app.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@nestjs/common'; 2 | 3 | @Injectable() 4 | export class AppService { 5 | getHello(): string { 6 | return 'Hello World!'; 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/main.ts: -------------------------------------------------------------------------------- 1 | import { NestFactory } from '@nestjs/core'; 2 | import { AppModule } from './app.module'; 3 | 4 | async function bootstrap() { 5 | const app = await NestFactory.create(AppModule); 6 | 7 | await app.listen(process.env.PORT || 3000); 8 | } 9 | 10 | bootstrap(); 11 | -------------------------------------------------------------------------------- /src/users/dto/create-user.dto.ts: -------------------------------------------------------------------------------- 1 | export class CreateUserDto { 2 | name: string; 3 | 4 | email: string; 5 | 6 | password?: string; 7 | } 8 | -------------------------------------------------------------------------------- /src/users/dto/update-user.dto.ts: -------------------------------------------------------------------------------- 1 | import { PartialType } from '@nestjs/mapped-types'; 2 | import { CreateUserDto } from './create-user.dto'; 3 | 4 | export class UpdateUserDto extends PartialType(CreateUserDto) {} 5 | -------------------------------------------------------------------------------- /src/users/entities/user.entity.ts: -------------------------------------------------------------------------------- 1 | export class User {} 2 | -------------------------------------------------------------------------------- /src/users/users.controller.spec.ts: -------------------------------------------------------------------------------- 1 | import { Test, TestingModule } from '@nestjs/testing'; 2 | import { UsersController } from './users.controller'; 3 | import { UsersService } from './users.service'; 4 | 5 | describe('UsersController', () => { 6 | let controller: UsersController; 7 | 8 | beforeEach(async () => { 9 | const module: TestingModule = await Test.createTestingModule({ 10 | controllers: [UsersController], 11 | providers: [UsersService], 12 | }).compile(); 13 | 14 | controller = module.get(UsersController); 15 | }); 16 | 17 | it('should be defined', () => { 18 | expect(controller).toBeDefined(); 19 | }); 20 | }); 21 | -------------------------------------------------------------------------------- /src/users/users.controller.ts: -------------------------------------------------------------------------------- 1 | import { 2 | Body, 3 | Controller, 4 | Delete, 5 | Get, 6 | Param, 7 | Patch, 8 | Post, 9 | } from '@nestjs/common'; 10 | import { CreateUserDto } from './dto/create-user.dto'; 11 | import { UpdateUserDto } from './dto/update-user.dto'; 12 | import { UsersService } from './users.service'; 13 | 14 | @Controller('users') 15 | export class UsersController { 16 | constructor(private readonly usersService: UsersService) {} 17 | 18 | @Post() 19 | create(@Body() createUserDto: CreateUserDto) { 20 | return this.usersService.create(createUserDto); 21 | } 22 | 23 | @Get() 24 | findAll() { 25 | return this.usersService.findAll(); 26 | } 27 | 28 | @Get(':id') 29 | findOne(@Param('id') id: string) { 30 | return this.usersService.findOne(+id); 31 | } 32 | 33 | @Patch(':id') 34 | update(@Param('id') id: string, @Body() updateUserDto: UpdateUserDto) { 35 | return this.usersService.update(+id, updateUserDto); 36 | } 37 | 38 | @Delete(':id') 39 | remove(@Param('id') id: string) { 40 | return this.usersService.remove(+id); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/users/users.module.ts: -------------------------------------------------------------------------------- 1 | import { Module } from '@nestjs/common'; 2 | import { UsersService } from './users.service'; 3 | import { UsersController } from './users.controller'; 4 | 5 | @Module({ 6 | controllers: [UsersController], 7 | providers: [UsersService] 8 | }) 9 | export class UsersModule {} 10 | -------------------------------------------------------------------------------- /src/users/users.service.spec.ts: -------------------------------------------------------------------------------- 1 | import { Test, TestingModule } from '@nestjs/testing'; 2 | import { UsersService } from './users.service'; 3 | 4 | describe('UsersService', () => { 5 | let service: UsersService; 6 | 7 | beforeEach(async () => { 8 | const module: TestingModule = await Test.createTestingModule({ 9 | providers: [UsersService], 10 | }).compile(); 11 | 12 | service = module.get(UsersService); 13 | }); 14 | 15 | it('should be defined', () => { 16 | expect(service).toBeDefined(); 17 | }); 18 | }); 19 | -------------------------------------------------------------------------------- /src/users/users.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@nestjs/common'; 2 | import { CreateUserDto } from './dto/create-user.dto'; 3 | import { UpdateUserDto } from './dto/update-user.dto'; 4 | 5 | @Injectable() 6 | export class UsersService { 7 | create(createUserDto: CreateUserDto) { 8 | return 'This action adds a new user'; 9 | } 10 | 11 | findAll() { 12 | return `This action returns all users`; 13 | } 14 | 15 | findOne(id: number) { 16 | return `This action returns a #${id} user`; 17 | } 18 | 19 | update(id: number, updateUserDto: UpdateUserDto) { 20 | return `This action updates a #${id} user`; 21 | } 22 | 23 | remove(id: number) { 24 | return `This action removes a #${id} user`; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /test/app.e2e-spec.ts: -------------------------------------------------------------------------------- 1 | import { Test, TestingModule } from '@nestjs/testing'; 2 | import { INestApplication } from '@nestjs/common'; 3 | import * as request from 'supertest'; 4 | import { AppModule } from './../src/app.module'; 5 | 6 | describe('AppController (e2e)', () => { 7 | let app: INestApplication; 8 | 9 | beforeEach(async () => { 10 | const moduleFixture: TestingModule = await Test.createTestingModule({ 11 | imports: [AppModule], 12 | }).compile(); 13 | 14 | app = moduleFixture.createNestApplication(); 15 | await app.init(); 16 | }); 17 | 18 | it('/ (GET)', () => { 19 | return request(app.getHttpServer()) 20 | .get('/') 21 | .expect(200) 22 | .expect('Hello World!'); 23 | }); 24 | }); 25 | -------------------------------------------------------------------------------- /test/jest-e2e.json: -------------------------------------------------------------------------------- 1 | { 2 | "moduleFileExtensions": ["js", "json", "ts"], 3 | "rootDir": ".", 4 | "testEnvironment": "node", 5 | "testRegex": ".e2e-spec.ts$", 6 | "transform": { 7 | "^.+\\.(t|j)s$": "ts-jest" 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /tsconfig.build.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./tsconfig.json", 3 | "exclude": ["node_modules", "test", "dist", "**/*spec.ts"] 4 | } 5 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "module": "commonjs", 4 | "declaration": true, 5 | "removeComments": true, 6 | "emitDecoratorMetadata": true, 7 | "experimentalDecorators": true, 8 | "allowSyntheticDefaultImports": true, 9 | "target": "es2017", 10 | "sourceMap": true, 11 | "outDir": "./dist", 12 | "baseUrl": "./", 13 | "incremental": true, 14 | "skipLibCheck": true, 15 | "strictNullChecks": false, 16 | "noImplicitAny": false, 17 | "strictBindCallApply": false, 18 | "forceConsistentCasingInFileNames": false, 19 | "noFallthroughCasesInSwitch": false 20 | } 21 | } 22 | --------------------------------------------------------------------------------