Backend Setup | NodeJS

Niraj Chaurasiya

02 July 2024

Table of Contents

The Introduction

    In this blog, I am going to write the all the process that we have discussed in the video.

    From installing (NODEJS) to creating a backend server with ExpressJS, we will gain a solid understanding in NodeJS.

Learning outcomes

  • Installing NodeJS in Windows, MacOS, and Linux
  • Creating a basic backend server with ExpressJS
  • Using environment file professionally

Installing NodeJS

    To start with making the backend with NodeJS, we need to make sure that we have NodeJS installed in our system.

    If you are unaware about NodeJS, it is a JavaScript runtime environment that lets us run Javascript on our system and in terminal.

    For more info: check (NODEJS) official website.

    NodeJS installation process

  • Installing in Linux OS
  • Lets start with the installation process in Linux OS

    Open your bash run these commands!

      
      sudo apt update
      sudo apt upgrade
      sudo apt-get update
      sudo apt-get upgrade
      sudo apt install nodejs
                    

    After the installation is finished, make sure to checkout the version!

      
      nodejs -v
      # It should show the current version of NodeJS
      npm -v
      # It should show the current version of npm
                    
  • Installing in Mac OS
  • Unlikely as the installation process in Linux OS where there is only one way to install NodeJS via command, there are two ways to install in MacOS.

    First one is prebuilt installer.

    Click here to download the prebuild installer package for MacOS.

    The second one is using bash

      
      # installs nvm (Node Version Manager)
      curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash
    
      # download and install Node.js (you may need to restart the terminal)
      nvm install 20
                    

    After the installation is finished, make sure to checkout the version!

      
      nodejs -v
      # It should show the current version of NodeJS
      npm -v
      # It should show the current version of npm
                    
  • Installing in Windows OS
  • Like as Mac OS, there are two ways to install NodeJS in Windows OS.

    First one is prebuilt installer.

    Click here to download the prebuild installer package for Windows OS.

    The second one is using powershell

      
      # installs fnm (Fast Node Manager)
      winget install Schniz.fnm
    
      # download and install Node.js
      fnm use --install-if-missing 20
                    

    After the installation is finished, make sure to checkout the version!

      
      nodejs -v
      # It should show the current version of NodeJS
      npm -v
      # It should show the current version of npm
                    

Creating a server with ExpressJS

    Now, we have successfully finished installing NodeJS in our system, lets create a simple server to check its working.

    There are two ways to initialize a server app.

    Using npm init and npm init -y

    You might wonder that what is the differences between in creating a server project with both of them because we have just added an -y at last. Lets us create a server to understand practically.

    Creating a server using npm init

      
      └─$ npm init              
      This utility will walk you through creating a package.json file.
      It only covers the most common items, and tries to guess sensible defaults.
    
      See 'npm help init' for definitive documentation on these fields
      and exactly what they do.
    
      Use 'npm install <pkg>' afterwards to install a package and
      save it as a dependency in the package.json file.
    
      Press ^C at any time to quit.
      package name: (folder_name_here) _
                    

    It means it will ask you to write every field inside terminal. After completing the steps, it should looks like:

      
      ┌──(niraj㉿kali)-[~/Desktop/js/nodejs/blog-mern-yt]
      └─$ npm init              
      This utility will walk you through creating a package.json file.
      It only covers the most common items, and tries to guess sensible defaults.
    
      See "npm help init" for definitive documentation on these fields
      and exactly what they do.
    
      Use "npm install <pkg>" afterwards to install a package and
      save it as a dependency in the package.json file.
    
      Press ^C at any time to quit.
      package name: (blog-mern-yt) 
      version: (1.0.0) 
      description: backend app for mern blog app
      entry point: (index.js) 
      test command: 
      git repository: 
      keywords: backend mern blog-app
      author: Niraj Chaurasiya
      license: (ISC) 
      About to write to /home/niraj/Desktop/js/nodejs/blog-mern-yt/package.json:
    
      {
        "name": "blog-mern-yt",
        "version": "1.0.0",
        "description": "backend app for mern blog app",
        "main": "index.js",
        "scripts": {
          "test": "echo "Error: no test specified" && exit 1"
        },
        "keywords": [
          "backend",
          "mern",
          "blog-app"
        ],
        "author": "Niraj Chaurasiya",
        "license": "ISC"
      }
    
    
      Is this OK? (yes) 
    
      ┌──(niraj㉿kali)-[~/Desktop/js/nodejs/blog-mern-yt]
      └─$ 
                    

    When it prompts above, it means a package.json file has been created inside the root foleder of the current directory.

    A package.json file looks something like:

      
      {
        "name": "blog-mern-yt",
        "version": "1.0.0",
        "description": "backend app for mern blog app",
        "main": "index.js",
        "scripts": {
          "test": "echo "Error: no test specified" && exit 1"
        },
        "keywords": [
          "backend",
          "mern",
          "blog-app"
        ],
        "author": "Niraj Chaurasiya",
        "license": "ISC"
      }
                    

    Now, lets initialize it by adding -y at last.

      
     ┌──(niraj㉿kali)-[~/Desktop/js/nodejs/blog-mern-yt]
     └─$ npm init -y
      Wrote to /home/niraj/Desktop/js/nodejs/blog-mern-yt/package.json:
    
      {
        "name": "blog-mern-yt",
        "version": "1.0.0",
        "description": "",
        "main": "index.js",
        "scripts": {
          "test": "echo "Error: no test specified" && exit 1"
        },
        "keywords": [],
        "author": "",
        "license": "ISC"
      }
    
      ┌──(niraj㉿kali)-[~/Desktop/js/nodejs/blog-mern-yt]
      └─$ 
      

    Now, our package.json looks like:

      
      {
        "name": "blog-mern-yt",
        "version": "1.0.0",
        "description": "",
        "main": "index.js",
        "scripts": {
          "test": "echo "Error: no test specified" && exit 1"
        },
        "keywords": [],
        "author": "",
        "license": "ISC"
      }
      

    In both the cases, it creates a package.json file but one with default value and the other with user entered value.

    So, this is the main difference in creating a package.json file with and without -y at last.

    Now, that we have successfully created a package.json file, lets create a basic backend server.

    Inside the same folder, create an index.js file as written inside the package.json as main file.

      
      Root folder
      --- index.js
      --- package.json
      

    We are going to make the server with ExpressJS.

    In case you don't know ExpressJS, it is a JS library that helps to create servers with NodeJS

    For more info: ExpressJS Official website

    Now, install express and nodemon using npm install express nodemon by using terminal.

    Open index.js file and write the following module code!

      
      import express from "express";
    
      const PORT = 8000;
      const app = express();
    
      app.listen(PORT, () => {
        console.log("Backend running on + ", PORT);
      });
      

    Now, open package.json and modify it.

      
      {
        "name": "backend",
        "version": "1.0.0",
        "description": "Backend for blog app",
        "main": "app.js",
        "type": "module",
        "scripts": {
          "start": "nodemon index.js" // changes here
        },
        "keywords": [],
        "author": "Niraj Chaurasiya",
        "license": "ISC",
        "dependencies": {
          "dotenv": "^16.4.5",
          "express": "^4.19.2",
          "nodemon": "^3.1.4"      
        },
        "devDependencies": {
          "@types/express": "^4.17.21"
        }
      }
      

    After making all the changes, run npm start.

    It should show:

      
      ┌──(niraj㉿kali)-[~/Desktop/js/nodejs/blog-mern-yt]
      └─$ npm start    
    
      > blog-mern-yt@1.0.0 start
      > nodemon index.js
    
      [nodemon] 3.1.4
      [nodemon] to restart at any time, enter "rs"
      [nodemon] watching path(s): *.*
      [nodemon] watching extensions: js,mjs,cjs,json
      [nodemon] starting node index.js
      Backend running on 8000
      

    Now, we have successfully created a basic backend server with Express!

    Open, http://localhost:8000, and you should see, cannot get /

Using environment file professionally

    Why to use environment file?

    The answer is simple, we don't want to expose our secret variables to public, right? Lets us suppose, you created a mongoDB connection string from their website with the help of your account. Being the owner, you don't want to anyone to mess with your DB, right? But, if you just put your connection string publicly in your project, than anyone can mess with your DB.

    Hence, there comes the use of environment variables. You can simply write all your variables in this file and it will be only available to you. Interesting, isn't it?

    Now, lets understand how we can configure environment variables in our project.

    First of all, to configure environment variables in our project, we need to install a package, "Dotenv".

      
      npm install dotenv
      

    After installing dotenv package, we can use it in our project with a line of code.

    Open index.js file, and update the code.

      
      import express from "express";
      import { configDotenv } from "dotenv"; // Add this line
      configDotenv(); // Add this line
    
      const PORT = process.env.PORT; // Update PORT
      const app = express();
    
      app.listen(PORT, () => {
        console.log("Backend running on + ", PORT);
      });
      

    After making all the changes, run npm start again.

    It should show same as previous:

      
      ┌──(niraj㉿kali)-[~/Desktop/js/nodejs/blog-mern-yt]
      └─$ npm start    
    
      > blog-mern-yt@1.0.0 start
      > nodemon index.js
    
      [nodemon] 3.1.4
      [nodemon] to restart at any time, enter "rs"
      [nodemon] watching path(s): *.*
      [nodemon] watching extensions: js,mjs,cjs,json
      [nodemon] starting node index.js
      Backend running on 8000
      

    #TIP

    The above code works great but there is one problem, when we want to give access to any of the other file than index.js, we need to again cnfigure add those two lines.

    So, whats the permanent solution here?🤔

    Here comes an interesting way, we need to make changes inside our package.json file.

    Open your package.json and update the start command.

      
      {
        "name": "backend",
        "version": "1.0.0",
        "description": "Backend for blog app",
        "main": "app.js",
        "type": "module",
        "scripts": {
          "start": "nodemon -r dotenv/config --experimental-json-modules app.js" // changes here
        },
        "keywords": [],
        "author": "Niraj Chaurasiya",
        "license": "ISC",
        "dependencies": {
          "dotenv": "^16.4.5",
          "express": "^4.19.2",
          "mongoose": "^8.4.3",
          "nodemon": "^3.1.4"
        },
        "devDependencies": {
          "@types/express": "^4.17.21"
        }
      }
      

    This will solve the issue and works without importing dotenv in every file.

This blog is a solid overview about the content of the video, for full explaination about all the codes, refer the video embeded below!

Follow me on X: https://twitter.com/@loveforrobotics

My YouTube channel link where I share amazing videos like this: https://youtube.com/@niraj.chaurasiya

Playlist video on YouTube

https://youtube.com/playlist?list=PLYeR6R4wMO-8ToOG8X7vA7ELDdSX9D2w-&si=w0rpCeXJQYodean7

Tags

mern

blog-app