Deploying Backend code in production

Deploying backend code in production from scratch ...

Followed Hitesh Choudhary sir's video :

Firstly, open VS code and a new directory, name it whatever you want, let's say BackendProdTest

Open new terminal and type npm init

This will create a package.json file in your directory. We can also add a script to the package.json - "start" : "node index.js"

Then we can type npm run start in the terminal, which will help us run the script. We'll be using express (web framework for Node.js) to build the backend. To install express , type in a new terminal -

npm install express

we can observe in the package.json file, that express is now present in the dependencies, which implies that it has been successfully installed.

Then, we will copy a Hello World code from express's official website. Link :https://expressjs.com/en/starter/hello-world.html . Add a few get requests if you want.

const express = require('express') 

const app = express() 

const port = 3000

app.get('/', (req, res) => { res.send('Hello World!') })

app.get('/google',(req,res) => {res.send('Google start')})

app.listen(port, () => { console.log(`Example app listening on port ${port}`) })

Paste this code in index.js and then from the terminal : npm run start

Now, go to localhost:3000 to see the output "Hello World " on the browser and to localhost:3000/google to see the output "Google start"

Now moving forward , we will install dotenv package in terminal

npm i dotenv

Add require('dotenv').config in the code. env files are created to keep data that is sensitive such as passwords, database URL and ports.

Deploy this code on Github in an empty repository. To deploy, open your terminal in vs code and give commands as follows (after creating a repo on Github ):

git init

git add README.md

git add .

git commit -m "First Commit"

git branch -M main

git remote add origin github.com/Akshatchaube01/reponame.git

git push -u origin main

Now, go to DigitalOcean -> Create -> App

1 Resource : Select Github and select your repository. Select a plan - Basic or Pro for your web service. Minimum fees for basic is $5

2 Environment Variables : Add an env variable in global and in BackendProdTest - PORT 3000 . Similarly you can add more env variables if you want. It may override the port automatically.

3 Info : Select region

4 Review : Recheck all the details

After a few minutes, the build will be successfully deployed. Go to Apps and you can find the Live App URL, we can change the live App URL by adding a custom domain name.

If you make any changes locally, they won't be reflected on the live App URL, to make those changes visible, you need to push the updated code on your Github repository.

Your basic backend code has been deployed !