Chapter 11

Deploy Nest.js Application

Configure Development and Production Environment



This lesson covers the deployment of a Nest.js project to Railway, detailing the necessary configurations. It requires setting up distinct .env files for development and production environments. Nest.js best practices include using environment-specific configuration files to manage different settings for development, testing, and production, ensuring sensitive data is not exposed. Proper management of environment variables is crucial for security and flexibility in different deployment scenarios.

Step 1: Create New Account at the Railway

Create a new account at Railway.

Step 2: Create a new Project

After creating an account at Railway you have to create a new project, connect your Github account with Railway

Step 3: add NODE_ENV in configuration file

The NODE_ENV has not been included in configuration.ts. Including it would enable access to NODE_ENV through ConfigService, which is a best practice in NestJS for maintaining environment-based configurations, thereby facilitating easier management and scalability of the application’s settings.

//configuration.ts

NODE_ENV: process.env.NODE_ENV;



Step 4: Refactor the envFile path in AppModule

A separate environment file is required for each development stage, necessitating the addition of a dynamic environment file path. NestJS supports environment-specific configuration through its configuration module, a best practice that ensures the separation of concerns and facilitates different settings for development, staging, and production environments.

//app.module.ts

ConfigModule.forRoot({

  envFilePath: [`${process.cwd()}/.env.${process.env.NODE_ENV}`],

  isGlobal: true,

  load: [configuration],

  validate: validate,

}),



process.cwd() gives you the current working directory

Step 4: Add NODE_ENV for development and production script

Set the NODE_ENV configuration in package.json file

"start:dev": "NODE_ENV=development nest build --webpack --webpackPath webpack-hmr.config.js --watch",

"start:prod": "NODE_ENV=production node dist/main",



Step 5: Test the Application

The application is executable by initiating the project in either development or production mode. In NestJS, this is typically managed by environment-specific configuration files, which is a best practice for maintaining separation between development and production settings, ensuring that environment variables and settings are correctly applied for each scenario.



Pushing your source code



In this lesson, the focus is on pushing the source code to GitHub and establishing a connection between the GitHub repository and the Railway project. As a best practice in NestJS development, it's recommended to include a .gitignore file to prevent the versioning of environment-specific files and node_modules, thus ensuring the repository remains clean and manageable. Additionally, integrating continuous integration tools can streamline deployment workflows, a strategy aligned with high-quality software development processes.

Step 1: Create a GitHub Repository

create a new GitHub repository and push the source code to that repository

git remote add origin <Your repo Link>

git branch -M main

git push -u origin main



Don't push the files: .env, .env.development, .env.production to your GitHub repository. Add this as a restriction in the .gitignore

.env

.env.development

.env.production




Deploy Nest.js Project



The deployment of a Nest.js project to Railway requires configuring the project's environment variables and settings within the Railway platform. Ensuring that the database and other services align with the Railway deployment specifications is a critical step for smooth operation, which aligns with best practices for cloud deployment.

Step 1: Connect your GitHub Repo to Railway Project

A new account has been created at Railway, and it requires the selection of a GitHub repository. Connecting the repository is necessary at this stage.

Upon selecting the repository, the application deployment will commence.

Additionally, the application status can be monitored by checking the logs.

Step 2: Create a Database

Upon navigating to the project on Railway, a new database can be created with a simple right-click on the project dashboard; the Postgres Database must be selected.

Step 3: Copy the Database Configurations

The database has been created successfully. The database credentials can be obtained by visiting the connection tab.

The deployment of a Nest.js project to Railway requires configuring the project's environment variables and settings within the Railway platform. Ensuring that the database and other services align with the Railway deployment specifications is a critical step for smooth operation, which aligns with best practices for cloud deployment.

Step 1: Connect your GitHub Repo to Railway Project

A new account has been created at Railway, and it requires the selection of a GitHub repository. Connecting the repository is necessary at this stage.

Upon selecting the repository, the application deployment will commence.

Additionally, the application status can be monitored by checking the logs.

Step 2: Create a Database

Upon navigating to the project on Railway, a new database can be created with a simple right-click on the project dashboard; the Postgres Database must be selected.

Step 3: Copy the Database Configurations

The database has been created successfully. The database credentials can be obtained by visiting the connection tab.

DB_HOST=containers-us-west-89.railway.app

DB_PORT=5673

USERNAME=postgres

PASSWORD=PaX7MXpvWogZoxvcunkL

DB_NAME=railway



You have to copy your configurations and save it to .env.production file

Step 4: Set the Environment Variables for your Project

Now you have to go to your Nest.js project and you will find the Variable tab here




You have to copy your .env.production and save it here

Now it is going to start deploying the project and your project will be running successfully



Step 5: Test the Application

Now you can test the application by sending the signup request from your live api



You will see this error

It means there is no users table in your Railway Postgres database. We have to migrate your database to the production

In the next lesson, you are going to learn how to migrate the database in the production



Install DotEnv



In the previous video, we got this issue

Step 1: Run the Migration

You will get this error when you run the migration

Step 2: Set the Environment to Production using the export command

You can set the NODE_ENV to production to run the build command for the production database

Step 3: Run the migration again

When you run the migration again after setting up production NODE_ENV you will get the undefined env variables in the data-source.ts file. Now the NODE_ENV is the production, you can see below

Step 4: Install the dotenv package

The issue has been identified within the data-source.ts file, which fails to retrieve values from the .env.production file. Installation of the dotenv package in the application is required to ensure environment variables are managed and loaded correctly, which aligns with best practices for maintaining a secure and configurable codebase.

npm install dotenv



Step 5: Run the migration again to test it

When the migration is executed again, the same error persists. The forthcoming lesson will address the resolution of this error, highlighting a best practice which entails examining and refining the migration scripts to ensure idempotency, thereby preventing repetitive failure upon re-execution.




Fixing Env Bugs



Step 1: Create a .env file

Attempting to resolve the issue by specifying a custom path for the configuration may not yield the desired results. This approach, when unsuccessful, suggests that the problem lies elsewhere, potentially in the environment setup or file referencing.



Running the migration with the current setup continues to result in an error, suggesting that the env variables in data-source.ts are not being correctly defined or accessed. A best practice in such cases is to ensure that environment variables are being loaded properly, often by using a configuration management library or by verifying the path and export mechanism of the environment configuration file.



# USE IT FOR TYPEORM MIGRATION

PORT=3000

SECRET=HAD_12X#@



DB_HOST=containers-us-west-89.railway.app

DB_PORT=5673

USERNAME=postgres

PASSWORD=PaX7MXpvWogZoxvcunkL

DB_NAME=railway



You have to create a new .env file in the root directory of your project



Step 2: Generation the Migrations



Now you run the migration it will work like migration will be generated successfully



Step 3: Run the migration command

After the migration file has been generated successfully, execute the run migration command.



npm run migration:run



You will see this output






Step 4: Push the code to Repo

Source code must be pushed to the GitHub repository to trigger Railway's automatic redeployment of the application. Testing the application can then be conducted by sending a signup request, ensuring that continuous integration and delivery practices are followed for efficient workflow.

It's considered a best practice to include unit tests for the signup feature to validate functionality before pushing code changes. This ensures that the deployment pipeline maintains high-quality code promotion to production environments.

$7 bundle of my best NestJS + backend developer Courses.
More details coming soon.


Get the latest insights from the marketing world.

A blog that focuses on providing practical tips and strategies for businesses to improve their marketing and sales efforts.

Solutions

Helping you help your customers.

Sell smarter, better, and faster.

The insights you need to make smarter business decisions.