Backend Starter Template

Sandeep PatelSandeep Patel
7 min read

Check Node


  • Node.js Use for execute JavaScript

Verify Installation

node --version // This should display the installed Node.js version.

Project Initialization


npm init
  • This will ask several questions (like project name, version, description, entry point, etc.). You can press Enter to accept the defaults or provide your own values.

Quick Initialization

npm init -y
  • This generates a package.json file with default settings.

Version Format


  • version Format → Three dot format → 1.0.0

  • Called → Semantic Versioning (**SemVer)**

Semantic Versioning

Semantic Versioning (SemVer) is a versioning scheme for software that follows the format.

MAJOR.MINOR.PATCH
  • MAJOR → Increases when you make incompatible API changes.

  • MINOR → Increases when you add backward-compatible new features.

  • PATCH → Increases when you make backward-compatible bug fixes.

Example:
1.0.0 → Initial stable release.
1.1.0 → Added a new feature (backward compatible).
1.1.1 → Fixed a bug (backward compatible).
2.0.0 → Introduced breaking changes.

After running npm initpackage.json file is created.

{
  "name": "full-stack-template",
  "version": "1.0.0",
  "description": "template",
  "main": "index.js",
  "scripts": {
    "test": "echo \\"Error: no test specified\\" && exit 1"
  },
  "keywords": [
    "sandeepatel"
  ],
  "author": "",
  "license": "ISC"
}

Create entry point


index.js

console.log("Hello World");

Import third-party libraries using different methods


  • CommonJS (CJS) → require()
// This is the default module system in Node.js
const express = require('express'); // Importing Express.js
const app = express();
  • ES Modules (ESM) – import
// This is the modern way to import modules in JavaScript.
import express from 'express'; // Importing Express.js
const app = express();
  • Used when "type": "module" is set in package.json.

Environment variables - Project Kundalee


  • A .env file is used to store environment variables in a key-value format.

  • They are useful for keeping sensitive data (e.g., API keys, database credentials) secure and making applications more flexible across different environments (development, testing, production).

  • Do Not Commit .env Files – Add them to .gitignore.

  • Use .env.sample – Share expected variables without actual values.

Install

npm install dotenv

Create a .env file

// **.env.sample**

PORT=5000
DATABASE_URL=mongodb://localhost:27017/mydb

Client-Server Communication


  • The client (browser or frontend app) sends requests to the server using HTTP methods (GET, POST, PUT, DELETE).

  • The server (Node.js with Express.js) processes the request and sends a response.

Client-Server Communication in Node.js using Express.js

Express.js is a lightweight and fast **web framework for Node.js** that helps in building APIs and web applications.

Install Express.js

npm install express

Setup a basic Express server


index.js

import express from "express";

const app = express();
const port = 3000;

app.get("/", (req, res) => {
  res.send("Cohort!");
});

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

Run index.js

node index.js

Sending GET Request

In Browser → http://127.0.0.1:3000/

Speed Run

Syntax

app.get("/defineRoute", Callback)

Route always start with /

import express from "express";

const app = express();
const port = 3000;

// Run on Request
app.get("/", (req, res) => {
  res.send("Cohort!");
});

app.get("/sandeep", (req, res) => {
  console.log("Sandeep!");
});

app.get("/sandy", (req, res) => {
  console.log("Sandy!");
})

app.listen(port, () => {
  console.log(`Example app listening on port ${port}`);
})
  1. Restart index.js

  2. In Browser → http://127.0.0.1:3000/sandeep

  3. In Browser → http://127.0.0.1:3000/sandy

Automatically restarting the server


nodemon is a tool that helps develop Node.js applications by automatically restarting the server when file changes are detected.

  1. Installation → devDependencies
npm install -D nodemon
  1. Edit package.json
  • Change scripts
{
  "name": "full-stack-template",
  "version": "1.0.0",
  "description": "template",
  "main": "index.js",
  "type": "module",
  "scripts": {
    "start": "nodemon index.js"
  },
  "keywords": [
    "sandeepatel"
  ],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.21.2"
  },
  "devDependencies": {
    "nodemon": "^3.1.9"
  }
}
  1. Run
npm run start

PORT Define


For better management, use a .env file.

.env

  • Install npm i dotenv

  • dotenv Import in index.js

import express from "express";
import dotenv from "dotenv";

dotenv.config();

const app = express();
const port = process.env.PORT || 4000;

// Run on Request
app.get("/", (req, res) => {
  res.send("Cohort!");
});

app.get("/sandeep", (req, res) => {
  res.send("Sandeep!");
});

app.get("/sandy", (req, res) => {
  res.send("Sandy!");
})

app.listen(port, () => {
  console.log(`Example app listening on port ${port}`);
})
  • This imports the dotenv package, which is responsible for reading .env files

  • dotenv.config(); → This function reads the .env file and loads the variables into process.env.

CORS


CORS → Cross-Origin Resource Sharing

CORS Error resolve in Backend side.

CORS is a security feature implemented by web browsers to control how web pages can request resources from a different origin (domain, protocol, or port).

Package Installation

npm i cors

cors Import in index.js

import express from "express";
import dotenv from "dotenv";
import cors from "cors";

dotenv.config();

const app = express();
app.use(cors({
  origin: "<http://localhost:3000>", // Sirf yeh origin allow hoga
  methods: ["GET", "POST", "PUT", "DELETE"],  // Sirf inhi methods ki permission
  allowedHeaders: ["Content-Type", "Authorization"], // Sirf inhi headers ki permission
  credentials: true // Agar cookies ya authentication headers use ho rahe hain
}));

app.use(express.json()); // Body parser

const port = process.env.PORT || 4000;

// Run on Request
app.get("/", (req, res) => {
  res.send("Cohort!");
});

app.get("/sandeep", (req, res) => {
  res.send("Sandeep!");
});

app.get("/sandy", (req, res) => {
  res.send("Sandy!");
})

app.listen(port, () => {
  console.log(`Example app listening on port ${port}`);
})
  • app.use(express.json()); → When a client (frontend or API consumer) sends a request with a JSON body, Express does not automatically parse it. You need to explicitly tell Express to parse JSON data using express.json().

  • app**.**use(express**.**urlencoded({ extended**:** true }))**; →** When a user submits a form using the POST method, the data is sent in application/x-www-form-urlencoded format. Express does not parse this data automatically, so we need to use express.urlencoded().

Check

Database Connection


  • Use Database for Saving Data

  • Backend → mongoose → Database

mongoose

  • Mongoose is an ODM (Object Data Modeling) library for MongoDB and Node.js.

  • Schema-Based Models

  • Built-in Validation

Installation

npm install mongoose

Connecting to MongoDB

  1. Create /utils/db.js

  2. Create Account in Mongodb Atlas and Create Mongodb_URL

  3. Saved Mongodb_URL in .env

PORT=3000
MONGO_URL=

BASE_URL=http://127.0.0.1:3000

/utils/db.js

import mongoose from "mongoose";

const connectDB = async () => {
  try {
    await mongoose.connect(process.env.MONGO_URI);
    console.log(`MongoDB Connected`);
  } catch (error) {
    console.log("MongoDB Error", error);
  }
};

export default connectDB;

index.js

import express from "express";
import dotenv from "dotenv";
import cors from "cors";
import connectDB from "./utils/db.js";

dotenv.config();

const app = express();
app.use(cors({
  origin: process.env.BASE_URL, // Sirf yeh origin allow hoga
  methods: ["GET", "POST", "PUT", "DELETE"],  // Sirf inhi methods ki permission
  allowedHeaders: ["Content-Type", "Authorization"], // Sirf inhi headers ki permission
  credentials: true // Agar cookies ya authentication headers use ho rahe hain
}));

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

const port = process.env.PORT || 4000;

// Run on Request
app.get("/", (req, res) => {
  res.send("Cohort!");
});

app.get("/sandeep", (req, res) => {
  res.send("Sandeep!");
});

app.get("/sandy", (req, res) => {
  res.send("Sandy!");
})

// Connect to DB
connectDB();

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

Data Modeling


  1. Create /mode/User.mode.js Standard Structure

  2. Common Template

import mongoose from "mongoose";

const userSchema = new mongoose.Schema()

const User = mongoose.model("User", userSchema); 
export default User;

User Schema

import mongoose from "mongoose";

const userSchema = new mongoose.Schema({
  name: String,
  email: String,
  password: String,
  role: {
    enum: ["user", "admin"],
    default: "user"
  },
  isverified: {
    type: Boolean,
    default: false
  },
  verificationToken: {
    type: String
  },
  resetPasswordToken: {
    type: String
  },
  resetPasswordExpire: {
    type: Date
  }
}, { timestamps: true });

const User = mongoose.model("User", userSchema);

export default User;

Create a separate Route file

/routes/user.routes.js

Syntax

import express from "express";

const router = express.Router();

export default router;
import express from "express";
import { registerUser } from "../controller/user.controller";

const router = express.Router();

router.get("/register", registerUser);

export default router;

// <http://127.0.0.1:3000/api/v1/users/register>

Create a separate Controller file

/controller/user.controller.js

const registerUser = async (req, res) => {
  res.send("Register User") // Bussiness Logic
}

export { registerUser };

Final index.js

import express from "express";
import dotenv from "dotenv";
import cors from "cors";
import connectDB from "./utils/db.js";

// Import All routes
import userRoutes from "./routes/user.routes.js";

dotenv.config();

const app = express();
app.use(cors({
  origin: process.env.BASE_URL, // Sirf yeh origin allow hoga
  methods: ["GET", "POST", "PUT", "DELETE"],  // Sirf inhi methods ki permission
  allowedHeaders: ["Content-Type", "Authorization"], // Sirf inhi headers ki permission
  credentials: true // Agar cookies ya authentication headers use ho rahe hain
}));

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

const port = process.env.PORT || 4000;

// Run on Request
app.get("/", (req, res) => {
  res.send("Cohort!");
});

app.get("/sandeep", (req, res) => {
  res.send("Sandeep!");
});

app.get("/sandy", (req, res) => {
  res.send("Sandy!");
})

// Connect to DB
connectDB();

// Use Routes
app.use("/api/v1/users", userRoutes);

app.listen(port, () => {
  console.log(`Example app listening on port ${port}`);
})
0
Subscribe to my newsletter

Read articles from Sandeep Patel directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Sandeep Patel
Sandeep Patel

Software Developer | Freelancer