BBlogspage

Quick and Easy Backend Development Environment Setup

Quick and Easy Backend Development Environment Setup

Like me, for every front-end developer, backend development environment setup looks like absolute rocket science and a hard-to-nail task. When I moved from standard HTML, CSS, and JavaScript files to React, I then understood what the front-end setup looks like, and that helped me a lot while building the backend setup.

Let’s jump into VS Code and let’s get our hands dirty!!!

1. package.json

Once we create a folder and open it in VS Code, the very first step is to go ahead and create a package.json file.

Run the below-mentioned command in the terminal to create it:

Bash

npm init

This command asks questions as follows:

  • package name: React Backend
  • version: 1.0.0 (mention any version of your app)
  • description: React, Node.js project (project description)
  • entrypoint: server.js (This will be the entry door for your backend, like index.html for frontend)
  • test command: (test command if you have any, or can be kept blank)
  • git repository: (git repository of the project, or can be blank)
  • keywords: React, Node, blogspage (any keywords related to the project)
  • author: Ravindra (The lead developer or programmer of the project)
  • license: ISC (license info if you have any)

There is also a shortcut to skip all the above questions and create a package.json with default values:

Bash

npm init -y

The above command will create a package.json file automatically with all the default configurations.

2. Create a folder structure

If you are willing to write all the code in one file, you could probably do that, but your mind will blow after a few lines of code since everything is mixed. Hence, good programming practice involves structuring the code across multiple files and folders to increase the readability and maintainability of the code.

Create a folder structure as below. It’s not the final blueprint; as you keep adding functionality to your code, you will probably need to create more folders and files.

  • Root folder – The main folder you created first and launched in VS Code.
  • public – Folder to keep publicly available assets and temporary files.
  • src – This folder will contain all your source code.
    • controllers – Write all the controllers in this folder, which will handle the main actions.
    • db – It’s always good to separate the database connection-related code into a separate folder/file.
    • middlewares – Write all your middlewares here and integrate them later with app.use().
    • models – In order to work with the MongoDB database, we need mongoose to create database Schemas and models.
    • routers – Create a separate route file for each controller.
    • util – If you have some repetitive functions that will be called everywhere, create them here. (e.g., ApiResponse formatter, ApiError formatter, etc.)

3. Dot files

Once we have created a folder structure, let’s dive in and create our essential configuration files in the root directory.

.env

Environmental variables are key points to run the application. Environmental variables could be a security threat if exposed, compromising the application. Hence, we have to keep them secured.

The .env file looks like this:

Code snippet

PORT=8000
ORIGIN=http://localhost:5173
MONGO_DB_URL=mongodb+srv://<db_user>:<db_password>@cluster-pract.ehws0hg.mongodb.net

.gitignore

While we are pushing the production-ready code on GitHub, we have to skip some files/folders from being pushed to git, considering performance and security. You can use online tools to generate this file (e.g., gitignore.io).

.prettierrc

When a large project has multiple team members working on it, it’s necessary to maintain a consistent code format across all developers. A Prettier configuration file helps create that consistency.

The .prettierrc file looks like this:

JSON

{
"singleQuote": false,
"bracketSpacing": true,
"tabWidth": 2,
"semi": true,
"trailingComma": "es5"
}

.prettierignore

Prettier will format all code files, but we still have some files that we don’t want to be formatted. We mention all these file names inside this .prettierignore file:

Plaintext

/.vscode
/node_modules
./dist
*.env
.env.*

4. Install the packages

Backend development involves multiple dependencies and packages to install and work with. Let's install the essentials: Express, Dotenv, Prettier, Mongoose, and Nodemon (optional).

Bash

npm install express dotenv prettier mongoose

5. Important backend files

Great, you have been reading along, and by this time, you have done so many things for the backend development environment setup. We have some important files that need to be created inside the src folder.

app.js

We will create an Express server here and attach most middlewares to the Express server in the app.js file.

JavaScript

import express from "express";

//create app
const app = express();

app.use(express.json());
app.use(express.urlencoded({ extended: true }));

export { app };

server.js

This file is the main entry point of your backend application. We run the backend server from server.js. Apart from running the server, all other tasks like routing, registering middlewares, and initializing the database connection will be taken care of from this file.

JavaScript

import { app } from './app.js';
import dotenv from 'dotenv';
import { connectDB } from './db/index.js';
import { errorhandler } from './middlewares/errorHandler.middleware.js';
import { addEmployeeRouter } from './routers/employee.router.js';

dotenv.config();

const PORT = process.env.PORT || 3000;

// routers
app.use("/api/employee", addEmployeeRouter);

connectDB()
.then(() => {
app.listen(PORT, () => {
console.log(`Server Started on Port ${PORT}`);
});
app.on("error", (e) => {
console.error(e);
});
})
.catch((e) => {
console.error("Error while connecting the database");
});

app.use(errorhandler);

constants.js

This file will be used specifically to declare constant values, which we don’t want to change throughout the code.

JavaScript

export const DB_NAME = "employeeDB";

Final edit and check in package.json

We have multiple functionalities available in the package.json file to initiate. One important configuration is to mention which JavaScript module we are using for development.

JSON

// CommonJS module (Default)
"type": "commonjs"

// ECMAScript module (What we need)
"type": "module"

Because we are using modern import/export syntax, we must change our type to "module".

Most of the time, developers want to see ongoing changes in the backend without manually restarting the server. The --watch flag in newer NodeJS versions instructs the server to implement new changes automatically.

Update your package.json scripts:

JSON

"scripts": {
"dev": "node --watch src/server.js"
}

If you have a large project, you can install the nodemon package instead, which ensures your server restarts automatically whenever any changes occur:

Bash

npm install nodemon --save-dev

There would be some additional helpful functions that you can create to make your life easier as you go. Congratulations! You have done the initial setup of your project. You can start writing the controllers, modules, and routers to make your backend functional.

Oh! We’ve reached the end of the article. I hope you’ve gained a solid understanding of how to do the initial setup for backend development. 😃

🚀 Follow me on Twitter for more tips and updates: @ravindra5k

💡 Check out my other articles:

  • Everything You Need to Know About JavaScript Functions – Beginner to Pro
  • 10 Tips to Write CSS Faster and More Efficiently for New Web Developers
  • React Fiber VS Virtual DOM: How React Optimizes UI Updates
  • Master the DOM and APIs by Building a Currency Converter App
  • JavaScript Data Types in Web Technology for Beginners
  • How to Create an Image Gallery with Filter Buttons in Just 10 Minutes!
  • Create Website Slider with HTML, CSS & Swiper.js!

Frequently Asked Questions

How many types of modules are there in JavaScript? In JavaScript, there are mainly two types of modules: 1) CommonJS (CJS) and 2) ES Modules (ESM / ES6 Modules).

How can I tell git not to push a specific list of files/folders to GitHub? We can create a .gitignore file in the root directory mentioning the list of files and directories (folders) that we don’t want to push to GitHub.

Where do we provide information to the backend server about the entry file? In general, in a Node.js project, there are two places where the entry file name is mentioned in the package.json:

  1. "main": "src/server.js"
  2. "scripts": { "start": "node src/server.js" }

We have mentioned .env in the .gitignore file and are not pushing it to production, so how will the deployment server be aware of our project environment variables? Every deployment server (like Vercel, Render, or Heroku) will have an option in its dashboard to configure environment variables directly on the server hosting platform. These will be securely injected and used by your backend server at runtime.