- [OPTIONAL] Modify
src/main.ts
to enable CORS:
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.enableCors();
await app.listen(process.env.PORT || 3000);
}
- Open
.gitignore
file and remove the following line to enable pushing the compiled javascript files to the remote repository so that we can download them on the server for hosting.
Remove /dist from .gitignore
- In
package.json
make sure that it contains scripts defined as
"build": "nest build",
"start": "nest start",
"start:prod": "node dist/main",
In case where you are hosting the application on a server like Heroku that can install dependencies you can include the following in the package.json file.
"postinstall": "npm run build",
this will automatically run after Heroku has finished installed the dependencies for the project.
- Some Hosting Providers use Procfile for running web applications, like Heroku, so create a file in the root of project named
Procfile
and add the following single line to it.
web:npm run start:prod
-
Delete the
dist
folder and runnpm run start
in command-line/terminal to create the latest version of compiled output files. (Deleting folder first is not necessary but it has proven helpful in some cases). -
Push your changes to GitHub Repository using these three basic commands:
git add . //Stage All Files including dist folder
git commit -m "doing it live"
git push
-
Setup your cloud instance on any platform such as:
- AWS EC2 Instance
- Digital Ocean
- Heroku
- A2Hosting
-
Clone the GitHub repository to the instance using the terminal.
-
Target your server to launch dist/main.js if required to specify.
In this way, NestJS app will be deployed.
In case of Heroku, create your application on Heroku
and install the CLI
.
Once you have the CLI installed, you will need to run heroku login
to log into your account through the CLI.
Then, run the following command to deploy the application to the Heroku server.
heroku git:remote -a MY-HEROKU-APP
There are a couple of final steps to take before pushing code up to Heroku. First, we need to make sure that the environment is configured correctly by running these commands:
heroku config:set NPM_CONFIG_PRODUCTION=false
heroku config:set NODE_ENV=production
The NODE_ENV config should already be set to production
by default, but we are changing NPM_CONFIG_PRODUCTION to false
. Since we are performing the TypeScript build on the server (this is what our postinstall script does) we need all of the devDependencies in package.json
for it to run properly. If NPM_CONFIG_PRODUCTION is set to true
the devDependencies won't be installed and it won't work.
Now you can push code up to Heroku. You can do that by running:
git add .
git commit -m "doing it live"
git push heroku master
why do you remove the dist folder from the .gitignore file?