๐ Node.js Backend : Pro Beginner Notes

Table of contents
- ๐ Table of Contents
- 1. Getting Started
- 2. require vs import
- 3. Managing Config with dotenv
- 4. Express Setup
- 5. Auto Reload with Nodemon
- 6. Handling CORS the Right Way
- 7. Handling JSON and Form Data
- 8. MongoDB Setup with Mongoose
- 9. Secure Password Reset Flow
- 10. Creating a User Model
- 11. API Structure: Routes, Controllers, Layers
- 12. Beginner Doubts Answered
- 13. Mini Project Ideas
- 14. Final Thoughts
- ๐ฌ Like this guide?
Want to build a clean, maintainable, and secure backend with Node.js, Express, MongoDB, and best practices? This guide takes you step-by-step โ from setup to real-world essentials like CORS, .env
configs, routes, and password resets.
๐ Table of Contents
- Getting Started
- require vs import โ Which One?
- Managing Config with dotenv
- Express Setup
- Auto Reload with Nodemon
- Handling CORS the Right Way
- Handling JSON and Form Data
- MongoDB Setup with Mongoose
- Secure Password Reset Flow
- Creating a User Model
- API Structure: Routes, Controllers, Layers
- Beginner Doubts Answered
- Mini Project Ideas
- Final Thoughts
1. Getting Started
Initialize Your Project
npm init -y
Install Dependencies
npm i express dotenv cors mongoose
npm i -D nodemon
Enable ES Modules
In your package.json
, add:
"type": "module"
2. require vs import
Syntax | Type | When to Use |
require() | CommonJS | Older Node.js projects |
import | ES Modules | Modern ES6+ projects |
๐ง Best Practice: Stick to one module system per project for consistency.
3. Managing Config with dotenv
Create a .env
file:
PORT=4000
MONGO_URL=mongodb+srv://username:password@cluster.mongodb.net/myDB
๐ Add
.env
to.gitignore
โ never expose secrets in version control.
Enable environment variables:
import dotenv from 'dotenv';
dotenv.config();
Based on The Twelve-Factor App methodology โ config should live outside code.
4. Express Setup
import express from 'express';
const app = express();
const port = process.env.PORT || 4000;
app.get('/', (req, res) => {
res.send('Hello from backend!');
});
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});
5. Auto Reload with Nodemon
Install Nodemon
npm i -D nodemon
Add to package.json
"scripts": {
"dev": "nodemon index.js"
}
Run the App
npm run dev
6. Handling CORS the Right Way
CORS (Cross-Origin Resource Sharing) lets your frontend talk securely to your backend.
Install and Configure
npm i cors
import cors from 'cors';
app.use(cors({
origin: 'http://localhost:3000',
credentials: true,
methods: ['GET', 'POST', 'PUT', 'DELETE']
}));
โ Allow only trusted domains.
7. Handling JSON and Form Data
Add middlewares:
app.use(express.json()); // JSON data
app.use(express.urlencoded({ extended: true })); // Form data
8. MongoDB Setup with Mongoose
Install
npm i mongoose
Create DB Utility โ utils/db.js
import mongoose from 'mongoose';
import dotenv from 'dotenv';
dotenv.config();
const connectDB = () => {
mongoose.connect(process.env.MONGO_URL)
.then(() => console.log("โ
MongoDB connected"))
.catch(() => console.error("โ DB connection failed"));
};
export default connectDB;
Use in index.js
import connectDB from './utils/db.js';
connectDB();
โ ๏ธ Encode special characters in MongoDB URI (e.g.,
@ โ %40
)
9. Secure Password Reset Flow
Step-by-Step
Request Token
- User submits email
- Backend creates token and expiry
- Send via email
Verify Token
- Check existence & expiry
Submit New Password
- Validate token
- Hash password using
bcrypt
- Save to DB
๐ก๏ธ Security Tips
- Hash the token before storing in DB
- Expire tokens in 15โ60 min
- Rate-limit reset requests
- Never reveal if email exists
10. Creating a User Model
// models/User.model.js
import mongoose from 'mongoose';
const userSchema = new mongoose.Schema({
name: String,
email: String,
password: String,
role: { type: String, enum: ['user', 'admin'], default: 'user' },
isVerified: { type: Boolean, default: false },
verificationToken: String,
resetPasswordToken: String,
resetPasswordExpires: Date
}, { timestamps: true });
const User = mongoose.model('User', userSchema);
export default User;
๐ก Financial data? Store in lowest denomination (e.g., paise, not rupees)
11. API Structure: Routes, Controllers, Layers
// controllers/user.controller.js
const registerUser = async (req, res) => {
res.send("User registered successfully");
};
export { registerUser };
Routes
// routes/user.routes.js
import express from 'express';
import { registerUser } from '../controllers/user.controller.js';
const router = express.Router();
router.get('/register', registerUser);
export default router;
Use in Entry File
import userRoutes from './routes/user.routes.js';
app.use('/api/v1/users', userRoutes);
Now visiting /api/v1/users/register
hits your controller!
12. Beginner Doubts Answered
Q: app.json()
vs express.json()
?\
A: express.json()
is the correct middleware โ app.json()
doesn't exist.
Q: What if I have double slashes in a route?\
A: /api//register
= /api/register
. But avoid them.
Q: Do I need to return res.send()
?\
A: Not necessarily โ it's sufficient to just call res.send()
.
Q: How to share .env securely?\ A:
- Share via WhatsApp or password managers
- Add a
.env.sample
- Use Infisical for secrets management
13. Mini Project Ideas
Controller
Pick one and go deep!
- LMS โ Learning Management System
- CMS โ Content Management System
- HMS โ Hospital Management System
- BMS โ Billing Management System
Build one full-stack app well instead of five half-done ones.
14. Final Thoughts
โ
Keep code layered: routes โ controllers โ services\
โ
Use .env
for secrets\
โ
Use nodemon
for development\
โ
Understand why middleware, CORS, .env
, and tokens matter\
โ
Write secure, scalable backend code
๐ช "Zimmedariyon wale kandho ko thakna allow nahi hota."\ Keep shipping. Refine later. You're growing every day ๐
๐ฌ Like this guide?
Follow me for more dev tutorials on:
- Node.js
- MongoDB
- REST APIs
- Authentication
- Developer Career Tips
Subscribe to my newsletter
Read articles from shaikh sirajuddin directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
