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
- Introduction to Node.js
- Setting Up Development Environment
- Termux
- macOS
- Linux
- Windows
- Installing Libraries and Packages
- Node.js Fundamentals
- File System Operations
- Event-Driven Programming
- Building a Web Server without Express
- Getting Started with Express.js
- Routing and Modularisation
- REST API Design and CRUD Operations
- MVC Pattern
- MongoDB and Mongoose Integration
- Authentication & Authorisation with JWT
- Deployment
- 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
globalinstead ofwindow. - Provides core modules like
fs,http,os, andpath. - 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)
- Install Termux from F-Droid for latest updates.
- Update packages:
pkg update && pkg upgrade- Install Node.js:
-
pkg install nodejs-lts - Install Git (Necessary for termux especially):
pkg install git- Verify:
node -v npm -v
macOS
- Install Homebrew (package manager):
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"- Install Node.js (LTS recommended):
brew install node- Verify installation:
node -v npm -v- Install Git (optional):
brew install git
Linux (Ubuntu/Debian)
- Update system:
sudo apt update && sudo apt upgrade -y- Install Node.js and npm:
sudo apt install nodejs npm -y- Verify:
node -v npm -v
Windows (32 & 64-bit)
- Download Node.js LTS installer from nodejs.org.
- Run installer, check “Add Node.js to PATH”.
- Open Command Prompt:
node -vnpm -v- 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
| Symbol | Meaning |
|---|---|
^ | Update minor/patch versions |
~ | Update patch versions only |
* | Any version |
| None | Fixed 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/employeesand/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
- Install dependencies:
npm install bcrypt jsonwebtoken cookie-parser
2. Register user (hash password):
const hashed = await bcrypt.hash(password,10);
- 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'});
- Middleware verifies token and role for route protection.
- Logout clears refresh token.
Security Tips:
- Use HTTP-only cookies for refresh tokens.
- Keep access tokens short-lived.
Deployment
- Platforms: Glitch, Heroku, Vercel
- Use
.envfor 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