This guide is designed to teach you everything about building a secure, scalable REST API using Node.js, Express.js, MongoDB, and JWT-based authentication. It is tailored for Termux (Android), macOS, Linux, and Windows (32 & 64-bit). By the end, you will understand core concepts, installation, coding patterns, database integration, authentication, and deployment.


Table of Contents

  1. Introduction to Node.js
  2. Setting Up Development Environment
    • Termux
    • macOS
    • Linux
    • Windows
  3. Installing Libraries and Packages
  4. Node.js Fundamentals
  5. File System Operations
  6. Event-Driven Programming
  7. Building a Web Server without Express
  8. Getting Started with Express.js
  9. Routing and Modularisation
  10. REST API Design and CRUD Operations
  11. MVC Pattern
  12. MongoDB and Mongoose Integration
  13. Authentication & Authorisation with JWT
  14. Deployment
  15. Best Practices and Tips

Introduction to Node.js

Node.js is a JavaScript runtime built on Chrome’s V8 engine. Unlike browser JS:

  • It runs in a terminal/server environment.
  • Uses global instead of window.
  • Provides core modules like fs, http, os, and path.
  • Non-blocking I/O, ideal for scalable servers.
  • Package management through npm for installing libraries.

Advantages:

  • Fast, lightweight, and asynchronous.
  • Large ecosystem of libraries.
  • Perfect for building RESTful APIs, chat apps, and microservices.

Setting Up Development Environment

Termux (Android)

  1. Install Termux from F-Droid for latest updates.
  2. Update packages:
  3. pkg update && pkg upgrade
  4. Install Node.js:
  5. pkg install nodejs-lts
  6. Install Git (Necessary for termux especially):
  7. pkg install git
  8. Verify:
  9. node -v npm -v

macOS

  1. Install Homebrew (package manager):
  2. /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
  3. Install Node.js (LTS recommended):
  4. brew install node
  5. Verify installation:
  6. node -v npm -v
  7. Install Git (optional):
  8. brew install git

Linux (Ubuntu/Debian)

  1. Update system:
  2. sudo apt update && sudo apt upgrade -y
  3. Install Node.js and npm:
  4. sudo apt install nodejs npm -y
  5. Verify:
  6. node -v npm -v

Windows (32 & 64-bit)

  1. Download Node.js LTS installer from nodejs.org.
  2. Run installer, check “Add Node.js to PATH”.
  3. Open Command Prompt:
  4. node -v
  5. npm -v
  6. Optional: Install Git from git-scm.com.

Installing Libraries and Packages

Node.js uses npm (Node Package Manager) for installing packages. You can install globally or locally for a project.

Initialize a Project

mkdir myapi
cd myapi
npm init -y  # creates package.json

Installing Libraries Locally

npm install express mongoose bcrypt jsonwebtoken cors dotenv
  • express – Web framework
  • mongoose – MongoDB ODM
  • bcrypt – Password hashing
  • jsonwebtoken – JWT tokens
  • cors – Cross-Origin Resource Sharing
  • dotenv – Environment variables

Installing Packages Globally

npm install -g nodemon
  • nodemon automatically restarts the server during development.

Understanding package.json Symbols

SymbolMeaning
^Update minor/patch versions
~Update patch versions only
*Any version
NoneFixed version

Node.js Fundamentals

  • Modules: Use require() to import packages.
  • Global Objects: global, process, __dirname.
  • Async programming: callbacks, promises, async/await.
const fs = require('fs');
console.log(global);

File System Operations

Node.js fs module for reading/writing files:

const fs = require('fs');

// Read
fs.readFile('data.txt','utf8',(err,data)=>console.log(data));

// Write
fs.writeFileSync('newfile.txt','Hello Node.js');

// Append
fs.appendFile('newfile.txt','\nAppend this',err=>{ if(err) throw err });

// Delete
fs.unlink('oldfile.txt',err=>{ if(err) throw err });

Directories

if(!fs.existsSync('mydir')) fs.mkdirSync('mydir');
fs.rmdirSync('mydir');

Streams (large files)

const readStream = fs.createReadStream('large.txt');
const writeStream = fs.createWriteStream('copy.txt');
readStream.pipe(writeStream);

Event-Driven Programming

const EventEmitter = require('events');
const emitter = new EventEmitter();

emitter.on('message', msg => console.log('Event:', msg));
emitter.emit('message', 'Node.js Event Emitter!');

Practical Use: Logging events asynchronously to files ensures smooth server operations.


Building a Web Server without Express

const http = require('http');
const server = http.createServer((req,res)=>{
  if(req.url === '/'){
    res.writeHead(200,{'Content-Type':'text/html'});
    res.end('<h1>Home Page</h1>');
  }else{
    res.writeHead(404,{'Content-Type':'text/plain'});
    res.end('Page Not Found');
  }
});
server.listen(3000,()=>console.log('Server running on port 3000'));

Limitations: Manual routing, headers, and middleware management is tedious.


Getting Started with Express.js

const express = require('express');
const app = express();
const PORT = 3000;

app.use(express.json()); // JSON parsing
app.get('/', (req,res)=>res.send('Hello Express'));
app.listen(PORT, ()=>console.log(`Server running on port ${PORT}`));

Middleware Types:

  • Built-in: express.json(), express.static()
  • Custom: Request logger
  • Third-party: cors(), cookie-parser

Routing and Modularisation

const router = require('express').Router();
router.get('/employees',(req,res)=>res.json([{id:1,name:'Mustafa'}]));
module.exports = router;

const empRouter = require('./routes/employee');
app.use('/api', empRouter);

REST API Design and CRUD Operations

  • Create: POST /api/employees
  • Read: GET /api/employees and /api/employees/:id
  • Update: PUT /api/employees/:id
  • Delete: DELETE /api/employees/:id

Testing: Thunder Client, Postman, or curl.


MVC Pattern

  • Models: Define Mongoose schemas.
  • Controllers: Business logic, CRUD functions.
  • Routes: Map URLs to controllers.

Separation improves maintainability and scalability.


MongoDB and Mongoose Integration

1. Install Mongoose:

2. Set up MongoDB Atlas cluster.

npm install mongoose

Connect:

const mongoose = require('mongoose');
mongoose.connect(process.env.MONGO_URI,{
useNewUrlParser:true,
useUnifiedTopology:true
});

4. Define schema/model:

const employeeSchema = new mongoose.Schema({name:String,role:String});
const Employee = mongoose.model('Employee',employeeSchema);

5. Replace JSON CRUD with async Mongoose functions: find(), findOne(), create(), deleteOne().

Authentication & Authorisation with JWT

  1. Install dependencies:

npm install bcrypt jsonwebtoken cookie-parser

2. Register user (hash password):

const hashed = await bcrypt.hash(password,10);

  1. Generate JWT tokens (access + refresh):
const jwt = require('jsonwebtoken');
const token = jwt.sign({id:user._id,role:user.role},process.env.JWT_SECRET,{expiresIn:'15m'});
  1. Middleware verifies token and role for route protection.
  2. Logout clears refresh token.

Security Tips:

  • Use HTTP-only cookies for refresh tokens.
  • Keep access tokens short-lived.

Deployment

  • Platforms: Glitch, Heroku, Vercel
  • Use .env for secrets:
MONGO_URI=mongodb+srv://user:pass@cluster.mongodb.net/dbname
JWT_SECRET=mysecret
  • Integrate GitHub for version control and continuous deployment.

Best Practices

  • Keep routes modular.
  • Validate input with libraries like Joi.
  • Implement error handling and logging.
  • Use HTTPS in production.
  • Regularly update dependencies.

Conclusion

This guide covers everything from setup to deployment for building a secure REST API using Node.js, Express, MongoDB, and JWT. Following this guide will give you:

  • Strong foundation in Node.js and asynchronous programming
  • Full understanding of REST API design
  • Skills for authentication and role-based authorisation
  • Ability to deploy across multiple platforms, including Termux, macOS, Linux, and Windows


0 Comments

Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *