Node.js Examples
Learn by doing. Every example below can be opened in our online editor — change the code, press Run and see the result instantly.
Open the Try it Now editor »Node.js Introduction
Node.js Basics · 1 example// hello.js
const name = 'AgyanAdda';
console.log(`Hello from Node.js, ${name}!`);
console.log('Node version:', process.version);
// Run in the terminal:
// node hello.js
Output: Hello from Node.js, AgyanAdda! and the Node version, e.g. Node version: v22.x.x.
Node.js Installation
Node.js Basics · 1 examplenode -v
# v22.11.0 (your version may differ)
npm -v
# 10.9.0
# Try the REPL
node
> 2 + 3
5
> 'agyan'.toUpperCase()
'AGYAN'
> .exit
If node -v prints a version number, Node.js is installed correctly. .exit (or Ctrl+C twice) leaves the REPL.
Node.js Modules: CommonJS and ES Modules
Node.js Basics · 1 example// ---- CommonJS ----
// math.js
function add(a, b) { return a + b; }
module.exports = { add };
// app.js
const { add } = require('./math');
console.log(add(2, 3)); // 5
// ---- ES Modules (package.json has "type": "module") ----
// math.js
export function add(a, b) { return a + b; }
export default function square(n) { return n * n; }
// app.js
import square, { add } from './math.js';
import { readFile } from 'node:fs/promises';
console.log(add(2, 3), square(4)); // 5 16
Both print the same result. ES modules use import/export and need the .js extension in the path.
Node.js npm and package.json
Node.js Basics · 1 example{
"name": "my-api",
"version": "1.0.0",
"type": "module",
"main": "src/index.js",
"scripts": {
"start": "node src/index.js",
"dev": "node --watch src/index.js",
"test": "node --test"
},
"dependencies": {
"express": "^4.21.0"
},
"devDependencies": {
"nodemon": "^3.1.0"
}
}
npm run dev starts the app and restarts it when files change; npm start runs it normally. express is needed in production, nodemon only while developing.
Node.js Global Objects and process
Node.js Basics · 1 example// greet.js (run: node greet.js Asha 3)
const [, , name = 'friend', times = '1'] = process.argv;
for (let i = 0; i < Number(times); i++) {
console.log(`Hello, ${name}!`);
}
console.log('Running on:', process.platform);
console.log('Port from env:', process.env.PORT ?? 'not set');
if (!process.argv[2]) {
console.error('Tip: pass your name, e.g. node greet.js Asha');
process.exit(1);
}
node greet.js Asha 3 prints "Hello, Asha!" three times, then the platform and port. process.argv[0] is node and [1] is the script path, so user arguments start at index 2.
Node.js File System (fs)
Node.js Core Modules · 1 exampleimport { readFile, writeFile, mkdir } from 'node:fs/promises';
const FILE = 'data/notes.json';
async function loadNotes() {
try {
return JSON.parse(await readFile(FILE, 'utf8'));
} catch (err) {
if (err.code === 'ENOENT') return []; // file does not exist yet
throw err;
}
}
async function addNote(text) {
const notes = await loadNotes();
notes.push({ id: notes.length + 1, text, createdAt: new Date().toISOString() });
await mkdir('data', { recursive: true });
await writeFile(FILE, JSON.stringify(notes, null, 2));
return notes;
}
const notes = await addNote('Learn the fs module');
console.log(`You have ${notes.length} note(s)`);
The first run creates data/notes.json and prints "You have 1 note(s)". Each run adds another note to the file.
Node.js path and os Modules
Node.js Core Modules · 1 exampleimport path from 'node:path';
import os from 'node:os';
const file = path.join('uploads', 'photos', 'profile.JPG');
console.log(file); // uploads/photos/profile.JPG (\ on Windows)
console.log(path.extname(file).toLowerCase()); // .jpg
console.log(path.basename(file, '.JPG')); // profile
const gb = (bytes) => (bytes / 1024 ** 3).toFixed(1) + ' GB';
console.log({
platform: os.platform(),
cpus: os.cpus().length,
totalMemory: gb(os.totalmem()),
freeMemory: gb(os.freemem()),
home: os.homedir(),
});
Prints the joined path with the correct separator, the extension .jpg, the name profile, and an object such as { platform: 'win32', cpus: 8, totalMemory: '16.0 GB', ... }.
Node.js Events and EventEmitter
Node.js Core Modules · 1 exampleimport { EventEmitter } from 'node:events';
class OrderService extends EventEmitter {
pay(order) {
order.status = 'paid';
this.emit('paid', order);
}
}
const orders = new OrderService();
orders.on('paid', (o) => console.log(`Email: receipt sent for order #${o.id}`));
orders.on('paid', (o) => console.log(`Stock: reduced for ${o.items} item(s)`));
orders.once('paid', () => console.log('First sale of the day!'));
orders.on('error', (err) => console.error('Order error:', err.message));
orders.pay({ id: 101, items: 2 });
orders.pay({ id: 102, items: 1 });
The first pay() prints the email line, the stock line and "First sale of the day!". The second prints only the email and stock lines because once() runs a single time.
Node.js HTTP Module: Create a Web Server
Node.js Core Modules · 1 exampleimport http from 'node:http';
const server = http.createServer(async (req, res) => {
const url = new URL(req.url, 'http://localhost');
if (req.method === 'GET' && url.pathname === '/') {
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
return res.end('<h1>Home page</h1>');
}
if (req.method === 'GET' && url.pathname === '/api/hello') {
const name = url.searchParams.get('name') ?? 'Guest';
res.writeHead(200, { 'Content-Type': 'application/json' });
return res.end(JSON.stringify({ message: `Hello, ${name}` }));
}
if (req.method === 'POST' && url.pathname === '/api/echo') {
let body = '';
for await (const chunk of req) body += chunk;
res.writeHead(201, { 'Content-Type': 'application/json' });
return res.end(body);
}
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Not found');
});
server.listen(3000, () => console.log('Server running at http://localhost:3000'));
/ shows a heading, /api/hello?name=Asha returns {"message":"Hello, Asha"}, POST /api/echo returns the body you sent, and any other URL returns 404 Not found.
Node.js Streams and Buffers
Node.js Core Modules · 1 exampleimport { createReadStream, createWriteStream } from 'node:fs';
import { createGzip } from 'node:zlib';
import { pipeline } from 'node:stream/promises';
console.time('gzip');
await pipeline(
createReadStream('server.log'), // read in chunks
createGzip(), // transform: compress
createWriteStream('server.log.gz'), // write in chunks
);
console.timeEnd('gzip');
console.log('Done: server.log.gz created');
// Buffers
const buf = Buffer.from('Namaste');
console.log(buf); // <Buffer 4e 61 6d 61 73 74 65>
console.log(buf.toString('base64')); // TmFtYXN0ZQ==
The log file is compressed using little memory however large it is. The Buffer lines show the raw bytes of "Namaste" and its base64 form.
Node.js Event Loop
Asynchronous Programming · 1 exampleconsole.log('1: start');
setTimeout(() => console.log('5: setTimeout'), 0);
setImmediate(() => console.log('6: setImmediate'));
Promise.resolve().then(() => console.log('4: promise'));
process.nextTick(() => console.log('3: nextTick'));
console.log('2: end');
Output: 1: start, 2: end, 3: nextTick, 4: promise, 5: setTimeout, 6: setImmediate. Sync code runs first, then microtasks, then timers. (setTimeout vs setImmediate order can vary in the main script, but microtasks always come first.)
Node.js Callbacks
Asynchronous Programming · 1 exampleimport fs from 'node:fs';
import { promisify } from 'node:util';
// ❌ Callback style: nested and repetitive
fs.readFile('a.txt', 'utf8', (err, a) => {
if (err) return console.error(err.message);
fs.readFile('b.txt', 'utf8', (err, b) => {
if (err) return console.error(err.message);
fs.writeFile('ab.txt', a + b, (err) => {
if (err) return console.error(err.message);
console.log('Merged (callbacks)');
});
});
});
// ✅ Same task with promisify + async/await
const readFile = promisify(fs.readFile);
const writeFile = promisify(fs.writeFile);
try {
const a = await readFile('a.txt', 'utf8');
const b = await readFile('b.txt', 'utf8');
await writeFile('ab.txt', a + b);
console.log('Merged (async/await)');
} catch (err) {
console.error(err.message);
}
Both versions merge a.txt and b.txt into ab.txt. The async/await version is flat and has one place for error handling.
Node.js Promises and async/await
Asynchronous Programming · 1 exampleimport { setTimeout as wait } from 'node:timers/promises';
async function fetchUser(id) {
await wait(500); // pretend this is a database call
if (id === 0) throw new Error('User not found');
return { id, name: `User ${id}` };
}
console.time('sequential');
const a = await fetchUser(1);
const b = await fetchUser(2);
console.timeEnd('sequential'); // ~1000 ms
console.time('parallel');
const [c, d] = await Promise.all([fetchUser(3), fetchUser(4)]);
console.timeEnd('parallel'); // ~500 ms
const results = await Promise.allSettled([fetchUser(5), fetchUser(0)]);
results.forEach((r) => console.log(r.status, r.value?.name ?? r.reason.message));
// fulfilled User 5
// rejected User not found
try {
await fetchUser(0);
} catch (err) {
console.error('Caught:', err.message);
}
The parallel version takes about half the time. allSettled reports each result even when one fails, and try/catch handles the error from fetchUser(0).
Node.js Error Handling
Asynchronous Programming · 1 exampleclass AppError extends Error {
constructor(message, statusCode = 500) {
super(message);
this.name = 'AppError';
this.statusCode = statusCode;
}
}
class NotFoundError extends AppError {
constructor(what) { super(`${what} not found`, 404); }
}
async function getProduct(id) {
const products = { 1: 'Pen', 2: 'Notebook' };
if (!products[id]) throw new NotFoundError(`Product ${id}`);
return products[id];
}
try {
console.log(await getProduct(1)); // Pen
console.log(await getProduct(9));
} catch (err) {
if (err instanceof AppError) console.log(err.statusCode, err.message); // 404 Product 9 not found
else throw err;
}
process.on('unhandledRejection', (reason) => {
console.error('Unhandled rejection:', reason);
process.exit(1);
});
Prints Pen, then 404 Product 9 not found. Any promise rejection that nobody handles is logged and the process exits so a process manager can restart it.
Express.js Introduction
Express.js and Databases · 1 example// app.js
import express from 'express';
const app = express();
app.use(express.json());
app.use(express.static('public'));
app.get('/', (req, res) => {
res.send('<h1>Welcome to my Express app</h1>');
});
app.get('/api/time', (req, res) => {
res.json({ now: new Date().toISOString() });
});
app.use((req, res) => {
res.status(404).json({ error: 'Route not found' });
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Server: http://localhost:${PORT}`));
/ shows a heading, /api/time returns {"now":"2026-12-03T..."}, files in public/ are served directly, and other URLs return a 404 JSON error.
Express.js Routing
Express.js and Databases · 1 example// routes/users.js
import { Router } from 'express';
const router = Router();
const users = [{ id: 1, name: 'Asha' }, { id: 2, name: 'Ravi' }];
router.get('/', (req, res) => {
const q = (req.query.q ?? '').toLowerCase();
res.json(users.filter((u) => u.name.toLowerCase().includes(q)));
});
router.get('/:id', (req, res) => {
const user = users.find((u) => u.id === Number(req.params.id));
if (!user) return res.status(404).json({ error: 'User not found' });
res.json(user);
});
router.post('/', (req, res) => {
const user = { id: users.length + 1, name: req.body.name };
users.push(user);
res.status(201).json(user);
});
export default router;
// app.js
// import usersRouter from './routes/users.js';
// app.use('/api/users', usersRouter);
GET /api/users?q=as returns [{"id":1,"name":"Asha"}], GET /api/users/2 returns Ravi, /api/users/9 returns 404, and POST /api/users with {"name":"Neha"} returns 201 with the new user.
Express.js Middleware
Express.js and Databases · 1 exampleimport express from 'express';
const app = express();
// 1. Runs for every request
app.use((req, res, next) => {
const start = Date.now();
res.on('finish', () => console.log(`${req.method} ${req.url} ${res.statusCode} ${Date.now() - start}ms`));
next();
});
// 2. Route-level middleware
function requireApiKey(req, res, next) {
if (req.get('x-api-key') !== process.env.API_KEY) {
return res.status(401).json({ error: 'Invalid API key' });
}
next();
}
app.get('/api/secret', requireApiKey, (req, res) => res.json({ data: 'top secret' }));
app.get('/boom', (req, res, next) => next(new Error('Something broke')));
// 3. Error handler: four arguments, defined last
app.use((err, req, res, next) => {
console.error(err);
res.status(err.statusCode || 500).json({ error: 'Internal server error' });
});
app.listen(3000);
Every request is logged like "GET /api/secret 401 2ms". /api/secret needs the right x-api-key header. /boom is caught by the error handler, which returns a 500 JSON response.
Express.js Templates with EJS
Express.js and Databases · 1 example// app.js
import express from 'express';
const app = express();
app.set('view engine', 'ejs');
app.use(express.urlencoded({ extended: true }));
const posts = [{ title: 'Learn Node' }, { title: 'Learn Express' }];
app.get('/', (req, res) => res.render('index', { title: 'Blog', posts }));
app.post('/posts', (req, res) => {
posts.push({ title: req.body.title });
res.redirect('/');
});
app.listen(3000);
/* views/index.ejs
<%- include('partials/header', { title }) %>
<h1><%= title %></h1>
<% if (posts.length === 0) { %>
<p>No posts yet.</p>
<% } %>
<ul>
<% posts.forEach(post => { %>
<li><%= post.title %></li>
<% }) %>
</ul>
<form method="POST" action="/posts">
<input name="title" required> <button>Add</button>
</form>
*/
The home page lists the posts. Submitting the form adds a post and redirects back to the list. A title like <b>hi</b> is shown as text because <%= %> escapes it.
Building a REST API with Express
Express.js and Databases · 1 exampleimport express from 'express';
import cors from 'cors';
const app = express();
app.use(cors());
app.use(express.json());
let books = [{ id: 1, title: 'Atomic Habits', price: 499 }];
let nextId = 2;
function validate(body) {
if (!body.title || typeof body.title !== 'string') return 'title is required';
if (typeof body.price !== 'number' || body.price < 0) return 'price must be a positive number';
}
app.get('/api/books', (req, res) => res.json(books));
app.get('/api/books/:id', (req, res) => {
const book = books.find((b) => b.id === Number(req.params.id));
book ? res.json(book) : res.status(404).json({ error: 'Book not found' });
});
app.post('/api/books', (req, res) => {
const error = validate(req.body);
if (error) return res.status(400).json({ error });
const book = { id: nextId++, title: req.body.title, price: req.body.price };
books.push(book);
res.status(201).json(book);
});
app.put('/api/books/:id', (req, res) => {
const book = books.find((b) => b.id === Number(req.params.id));
if (!book) return res.status(404).json({ error: 'Book not found' });
const error = validate(req.body);
if (error) return res.status(400).json({ error });
Object.assign(book, { title: req.body.title, price: req.body.price });
res.json(book);
});
app.delete('/api/books/:id', (req, res) => {
books = books.filter((b) => b.id !== Number(req.params.id));
res.status(204).end();
});
app.listen(3000);
curl -X POST localhost:3000/api/books -H "Content-Type: application/json" -d '{"title":"Deep Work","price":399}' returns 201 with the new book. Sending no title returns 400 {"error":"title is required"}.
Node.js with MongoDB and Mongoose
Express.js and Databases · 1 example// models/Book.js
import mongoose from 'mongoose';
const bookSchema = new mongoose.Schema({
title: { type: String, required: true, trim: true },
author: { type: String, required: true },
price: { type: Number, min: 0, default: 0 },
tags: [String],
}, { timestamps: true });
export default mongoose.model('Book', bookSchema);
// app.js
import express from 'express';
import mongoose from 'mongoose';
import Book from './models/Book.js';
await mongoose.connect(process.env.MONGODB_URI);
const app = express();
app.use(express.json());
app.get('/api/books', async (req, res) => {
const books = await Book.find().sort({ createdAt: -1 }).limit(20);
res.json(books);
});
app.post('/api/books', async (req, res) => {
try {
res.status(201).json(await Book.create(req.body));
} catch (err) {
res.status(400).json({ error: err.message }); // validation errors
}
});
app.listen(3000);
POST /api/books with {"title":"Wings of Fire","author":"A.P.J. Abdul Kalam","price":299} saves a document with an _id and timestamps. Missing the author returns 400 with Mongoose's validation message.
Node.js with MySQL
Express.js and Databases · 1 example// db.js
import mysql from 'mysql2/promise';
export const pool = mysql.createPool({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
connectionLimit: 10,
});
// app.js
import express from 'express';
import { pool } from './db.js';
const app = express();
app.use(express.json());
app.get('/api/students/:id', async (req, res) => {
const [rows] = await pool.execute('SELECT id, name, course FROM students WHERE id = ?', [req.params.id]);
rows.length ? res.json(rows[0]) : res.status(404).json({ error: 'Student not found' });
});
app.post('/api/students', async (req, res) => {
const { name, course } = req.body;
const [result] = await pool.execute('INSERT INTO students (name, course) VALUES (?, ?)', [name, course]);
res.status(201).json({ id: result.insertId, name, course });
});
app.listen(3000);
GET /api/students/1 returns that student as JSON, and POST /api/students inserts a row and returns its new id. Placeholders keep both queries safe from SQL injection.
Node.js Authentication with JWT
Express.js and Databases · 1 exampleimport express from 'express';
import bcrypt from 'bcrypt';
import jwt from 'jsonwebtoken';
const app = express();
app.use(express.json());
const users = []; // use a real database in your app
const SECRET = process.env.JWT_SECRET;
app.post('/api/register', async (req, res) => {
const { email, password } = req.body;
if (users.some((u) => u.email === email)) return res.status(409).json({ error: 'Email already registered' });
users.push({ id: users.length + 1, email, password: await bcrypt.hash(password, 10) });
res.status(201).json({ message: 'Registered' });
});
app.post('/api/login', async (req, res) => {
const user = users.find((u) => u.email === req.body.email);
if (!user || !(await bcrypt.compare(req.body.password, user.password))) {
return res.status(401).json({ error: 'Invalid email or password' });
}
const token = jwt.sign({ sub: user.id, email: user.email }, SECRET, { expiresIn: '1h' });
res.json({ token });
});
function auth(req, res, next) {
const token = req.get('authorization')?.replace('Bearer ', '');
try {
req.user = jwt.verify(token, SECRET);
next();
} catch {
res.status(401).json({ error: 'Please log in' });
}
}
app.get('/api/me', auth, (req, res) => res.json({ id: req.user.sub, email: req.user.email }));
app.listen(3000);
Register, then log in to receive {"token":"eyJ..."}. GET /api/me with the header Authorization: Bearer eyJ... returns your id and email; without a valid token it returns 401.
Node.js File Upload with Multer
Express.js and Databases · 1 exampleimport express from 'express';
import multer from 'multer';
import path from 'node:path';
import crypto from 'node:crypto';
const app = express();
app.use('/uploads', express.static('uploads'));
const storage = multer.diskStorage({
destination: 'uploads/',
filename: (req, file, cb) => {
const ext = path.extname(file.originalname).toLowerCase();
cb(null, crypto.randomUUID() + ext);
},
});
const upload = multer({
storage,
limits: { fileSize: 2 * 1024 * 1024 },
fileFilter: (req, file, cb) => {
const ok = ['image/jpeg', 'image/png', 'image/webp'].includes(file.mimetype);
cb(ok ? null : new Error('Only JPG, PNG or WEBP images are allowed'), ok);
},
});
app.post('/api/avatar', upload.single('photo'), (req, res) => {
res.status(201).json({ url: `/uploads/${req.file.filename}`, size: req.file.size });
});
app.use((err, req, res, next) => res.status(400).json({ error: err.message }));
app.listen(3000);
Uploading a 500 KB JPG returns {"url":"/uploads/3f2a...jpg","size":512000}. A PDF or a 5 MB image returns 400 with an error message.
Node.js Environment Variables and Config
Advanced Node.js · 1 example// .env (not committed)
// PORT=4000
// NODE_ENV=development
// DATABASE_URL=mysql://root:secret@localhost/shop
// JWT_SECRET=change-me-to-a-long-random-string
// config.js
const required = ['DATABASE_URL', 'JWT_SECRET'];
for (const key of required) {
if (!process.env[key]) {
console.error(`Missing environment variable: ${key}`);
process.exit(1);
}
}
export const config = {
port: Number(process.env.PORT ?? 3000),
isProduction: process.env.NODE_ENV === 'production',
databaseUrl: process.env.DATABASE_URL,
jwtSecret: process.env.JWT_SECRET,
};
// Run: node --env-file=.env app.js
The app starts on port 4000 with the values from .env. If JWT_SECRET is missing it stops immediately with a clear message instead of failing later.
Node.js Fetch and Calling APIs
Advanced Node.js · 1 exampleasync function api(url, { method = 'GET', body, timeout = 5000 } = {}) {
const res = await fetch(url, {
method,
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${process.env.API_TOKEN ?? ''}`,
},
body: body ? JSON.stringify(body) : undefined,
signal: AbortSignal.timeout(timeout),
});
if (!res.ok) {
throw new Error(`API ${method} ${url} failed with ${res.status}`);
}
return res.status === 204 ? null : res.json();
}
try {
const todo = await api('https://jsonplaceholder.typicode.com/todos/1');
console.log(todo.title);
const created = await api('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
body: { title: 'Hello', body: 'From Node', userId: 1 },
});
console.log('Created post id:', created.id); // 101
} catch (err) {
console.error(err.name === 'TimeoutError' ? 'API too slow' : err.message);
}
Prints the title of todo 1 and "Created post id: 101" from the free test API. A 404, a 500 or a request taking more than 5 seconds is caught and reported.
Node.js Real-time Apps with Socket.IO
Advanced Node.js · 1 example// server.js
import express from 'express';
import { createServer } from 'node:http';
import { Server } from 'socket.io';
const app = express();
const server = createServer(app);
const io = new Server(server);
app.get('/', (req, res) => res.sendFile(import.meta.dirname + '/index.html'));
io.on('connection', (socket) => {
socket.broadcast.emit('system', 'A user joined the chat');
socket.on('chat', (text) => {
const message = String(text).slice(0, 500);
io.emit('chat', { id: socket.id.slice(0, 4), message, at: Date.now() });
});
socket.on('disconnect', () => io.emit('system', 'A user left'));
});
server.listen(3000, () => console.log('Chat on http://localhost:3000'));
/* index.html (client)
<script src="/socket.io/socket.io.js"></script>
<script>
const socket = io();
socket.on('chat', (m) => console.log(m.id + ': ' + m.message));
socket.emit('chat', 'Hello everyone!');
</script> */
Open http://localhost:3000 in two tabs: a message sent in one appears in both instantly, and joining or leaving shows a system message to the others.
Node.js Testing
Advanced Node.js · 1 example// utils.js
export const gst = (amount, rate = 18) => Math.round(amount * rate) / 100;
// app.js (export the app; start the server in server.js)
import express from 'express';
export const app = express();
app.get('/api/health', (req, res) => res.json({ status: 'ok' }));
// test/app.test.js
import { test } from 'node:test';
import assert from 'node:assert/strict';
import request from 'supertest';
import { gst } from '../utils.js';
import { app } from '../app.js';
test('gst calculates 18% by default', () => {
assert.equal(gst(1000), 180);
assert.equal(gst(1000, 5), 50);
});
test('GET /api/health returns ok', async () => {
const res = await request(app).get('/api/health');
assert.equal(res.status, 200);
assert.deepEqual(res.body, { status: 'ok' });
});
// Run: node --test
node --test finds files in the test folder and prints ✔ for each passing test, e.g. "✔ gst calculates 18% by default" and "pass 2".
Node.js Security Best Practices
Advanced Node.js · 1 exampleimport express from 'express';
import helmet from 'helmet';
import cors from 'cors';
import rateLimit from 'express-rate-limit';
const app = express();
app.use(helmet());
app.use(cors({ origin: ['https://agyanadda.com'], credentials: true }));
app.use(express.json({ limit: '100kb' }));
const loginLimiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
limit: 5, // 5 attempts per IP
message: { error: 'Too many login attempts. Try again later.' },
});
app.post('/api/login', loginLimiter, async (req, res) => {
const email = String(req.body.email ?? ''); // force string: blocks {"$gt": ""} tricks
const password = String(req.body.password ?? '');
// ... look up user with email, check bcrypt.compare(password, hash)
res.json({ ok: true });
});
app.listen(3000);
// Terminal: check dependencies for known vulnerabilities
// npm audit
// npm audit fix
helmet adds headers such as Content-Security-Policy, CORS allows only agyanadda.com, and the sixth login attempt within 15 minutes gets a 429 Too Many Requests response.
Deploying Node.js Apps
Advanced Node.js · 1 example# On the server (Ubuntu)
cd /var/www/my-api
git pull origin main
npm ci --omit=dev
# Start and keep it running
npm install -g pm2
pm2 start src/index.js --name my-api -i max
pm2 save
pm2 startup # run the command it prints
# /etc/nginx/sites-available/my-api
# server {
# server_name api.example.com;
# location / {
# proxy_pass http://127.0.0.1:3000;
# proxy_http_version 1.1;
# proxy_set_header Upgrade $http_upgrade; # needed for WebSockets
# proxy_set_header Connection 'upgrade';
# proxy_set_header Host $host;
# proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
# }
# }
sudo nginx -t && sudo systemctl reload nginx
sudo certbot --nginx -d api.example.com # free HTTPS
The API runs under PM2 on port 3000, restarts on crash or reboot, and is reached at https://api.example.com through Nginx with a free SSL certificate.
Node.js Best Practices and Project Structure
Advanced Node.js · 1 example// server.js
import { app } from './app.js';
import { pool } from './db.js';
const server = app.listen(process.env.PORT ?? 3000, () => {
console.log('Server started');
});
async function shutdown(signal) {
console.log(`${signal} received, shutting down...`);
server.close(async () => { // stop new connections, finish current ones
await pool.end(); // close database connections
console.log('Closed cleanly');
process.exit(0);
});
setTimeout(() => process.exit(1), 10_000).unref(); // force exit after 10s
}
process.on('SIGTERM', () => shutdown('SIGTERM'));
process.on('SIGINT', () => shutdown('SIGINT'));
When PM2, Docker or Ctrl+C stops the app, it finishes in-flight requests and closes the database instead of cutting users off mid-request.