Kazi Rahamatullah
Kazi Rahamatullah
AboutProjectsBlogContact
UsesBooks
ResumeView CV
Kazi Rahamatullah

© Copyright 2026 Kazi Rahamatullah

AboutProjectsBlogBooksUses
Twitter/XGitHubProduct HuntCodeSandbox
Back to Blog
MERNNode.jsExpressREST APIJWTnpm

MERN Course: Node.js & Express

Weeks 22–26 of the MERN syllabus — Node event loop, Express REST APIs, MongoDB integration, JWT auth, security, npm packages, and career guidance.

Jul 12, 202610 min read

Introduction

Node.js and Express complete the MERN back-end. This final syllabus section covers production API patterns, security, package publishing, and how to present your work.

Course Reference

Quick index

#TopicDescription
1Unleashing the Power of Node.jsNode.js runs JavaScript on the server with a non-blocking event loop.
2Asynchronous Programming in Node.jsConcurrent I/O with async/await keeps APIs responsive.
3Building Your First Express ApplicationExpress is minimal routing + middleware.
4Designing and Building a RESTful APIResources are nouns (/posts), HTTP verbs express actions.
5MongoDB + Mongoose with ExpressConnect once at startup; reuse the connection pool.
6Authentication with JWTRegister hashes passwords with bcrypt.
7API Security Best PracticesValidate and sanitize all input.
8Error Handling and DebuggingStructured logging (pino, winston) beats console.log in production.
9Project: Building a Real-World APICapstone API: e-commerce, social, or booking system with auth, MongoDB, validation (Zod), tests, and OpenAPI docs..
10Node.js Package Ecosystemnpm hosts reusable modules.
11Creating Your First npm PackageStructure: src/index.js, package.json with main/exports, README, MIT license.
12Testing and Maintaining PackagesUnit test public API surface.
13Final Package ProjectPublish a utility package: slug generator, env validator, or Express middleware.
14Node.js & Express Mastery RecapCore review: event loop, modules, async patterns, middleware pipeline, security, testing, deployment..
15MERN Career Paths & PortfolioRoles: front-end, back-end, full-stack, DevOps.

Week 22: Node.js & Express Foundations

1. Unleashing the Power of Node.js

Node.js runs JavaScript on the server with a non-blocking event loop. npm manages packages; CommonJS (require) and ESM (import) both exist — prefer ESM in new projects.

Example:

javascript
import fs from 'node:fs/promises'
 
const data = await fs.readFile('./posts.json', 'utf8')
console.log(JSON.parse(data).length, 'posts loaded')

Note

Node is single-threaded for JS — CPU-heavy work blocks the event loop. Offload to worker threads or separate services.

Tip

Apply this in your Week 22 course project before moving on.

Performance

Use streams for large files instead of reading entire buffers into memory.

Back to index


2. Asynchronous Programming in Node.js

Concurrent I/O with async/await keeps APIs responsive. Use Promise.allSettled when partial failures are acceptable.

Example:

javascript
const [users, posts] = await Promise.all([
  fetch('https://api.example.com/users').then((r) => r.json()),
  fetch('https://api.example.com/posts').then((r) => r.json()),
])

Note

Unhandled Promise rejections crash Node in modern versions — always attach .catch or use try/catch with await.

Tip

Apply this in your Week 22 course project before moving on.

Performance

Set fetch timeouts and circuit breakers for external APIs — do not hang requests indefinitely.

Back to index


3. Building Your First Express Application

Express is minimal routing + middleware. Middleware runs in order — auth, parsers, routes, error handler last.

Example:

javascript
import express from 'express'
 
const app = express()
app.use(express.json())
 
app.get('/api/health', (_req, res) => {
  res.json({ status: 'ok' })
})
 
app.listen(3001, () => console.log('API on :3001'))

Note

Always add a centralized error middleware with 4 args: (err, req, res, next) => {}.

Tip

Apply this in your Week 22 course project before moving on.

Performance

Enable gzip compression middleware for JSON responses over slow networks.

Back to index

Week 23: RESTful APIs & Database Integration

4. Designing and Building a RESTful API

Resources are nouns (/posts), HTTP verbs express actions. Return correct status: 200 OK, 201 Created, 204 No Content, 400 Bad Request, 404 Not Found.

Example:

javascript
app.get('/api/posts', async (_req, res, next) => {
  try {
    const posts = await Post.find().sort({ createdAt: -1 }).limit(20).lean()
    res.json(posts)
  } catch (err) {
    next(err)
  }
})
 
app.post('/api/posts', async (req, res, next) => {
  try {
    const post = await Post.create(req.body)
    res.status(201).json(post)
  } catch (err) {
    next(err)
  }
})

Note

Version APIs (/api/v1/posts) before external clients depend on your schema.

Tip

Apply this in your Week 23 course project before moving on.

Performance

Paginate list endpoints — never return unbounded collections.

Back to index


5. MongoDB + Mongoose with Express

Connect once at startup; reuse the connection pool. Disconnect gracefully on SIGTERM in container deployments.

Example:

javascript
import mongoose from 'mongoose'
 
await mongoose.connect(process.env.MONGODB_URI)
 
mongoose.connection.on('error', (err) => {
  console.error('MongoDB error:', err)
})

Note

Store MONGODB_URI in env vars. Use MongoDB Atlas IP allowlist + strong passwords in production.

Tip

Apply this in your Week 23 course project before moving on.

Performance

Set maxPoolSize appropriately for serverless vs long-running servers.

Back to index


6. Authentication with JWT

Register hashes passwords with bcrypt. Login returns JWT; protected routes verify Authorization: Bearer <token>.

Example:

javascript
import jwt from 'jsonwebtoken'
import bcrypt from 'bcryptjs'
 
const hash = await bcrypt.hash(password, 12)
const token = jwt.sign({ userId: user.id }, process.env.JWT_SECRET, { expiresIn: '7d' })
 
function auth(req, res, next) {
  const header = req.headers.authorization
  if (!header?.startsWith('Bearer ')) return res.status(401).json({ error: 'Unauthorized' })
  try {
    req.user = jwt.verify(header.slice(7), process.env.JWT_SECRET)
    next()
  } catch {
    res.status(401).json({ error: 'Invalid token' })
  }
}

Note

Use httpOnly cookies for browser apps when possible. Short-lived access tokens + refresh tokens for SPAs.

Tip

Apply this in your Week 23 course project before moving on.

Performance

bcrypt cost factor 10–12 balances security and login latency — do not go higher without profiling.

Back to index

Week 24: Security, Errors & Real-World API

7. API Security Best Practices

Validate and sanitize all input. Rate-limit auth routes. Helmet sets security headers; CORS restricts browser origins.

Example:

javascript
import helmet from 'helmet'
import rateLimit from 'express-rate-limit'
 
app.use(helmet())
app.use('/api/auth', rateLimit({ windowMs: 15 * 60 * 1000, max: 20 }))

Note

Never log passwords or tokens. Redact sensitive fields in error responses sent to clients.

Tip

Apply this in your Week 24 course project before moving on.

Performance

Rate limiting at edge (Cloudflare, Vercel) saves origin server work under attack.

Back to index


8. Error Handling and Debugging

Structured logging (pino, winston) beats console.log in production. Include request ID for tracing.

Example:

javascript
app.use((err, _req, res, _next) => {
  console.error(err)
  const status = err.status ?? 500
  res.status(status).json({
    error: status === 500 ? 'Internal server error' : err.message,
  })
})

Note

Distinguish operational errors (404, validation) from programmer errors (null reference) in logs.

Tip

Apply this in your Week 24 course project before moving on.

Performance

Async error wrappers (express-async-errors) avoid try/catch boilerplate in every route.

Back to index


9. Project: Building a Real-World API

Capstone API: e-commerce, social, or booking system with auth, MongoDB, validation (Zod), tests, and OpenAPI docs.

  • OpenAPI/Swagger docs for frontend team
  • Integration tests with supertest + test DB
  • Docker Compose for local Mongo + API

Note

Deploy API separately from React front-end — enables mobile apps and third-party integrations later.

Tip

Apply this in your Week 24 course project before moving on.

Performance

Horizontal scale stateless APIs behind a load balancer — store sessions in Redis or JWT, not memory.

Back to index


Week 25: Node.js Package Development

10. Node.js Package Ecosystem

npm hosts reusable modules. Study popular packages (express, zod, date-fns) for API design inspiration.

Note

Check bundle size and maintenance status before adding dependencies — npm audit for vulnerabilities.

Tip

Apply this in your Week 25 course project before moving on.

Performance

Prefer tree-shakeable ESM packages. Avoid importing entire lodash — use lodash-es per-method imports.

Back to index


11. Creating Your First npm Package

Structure: src/index.js, package.json with main/exports, README, MIT license. Publish with npm publish --access public.

Example:

json
{
  "name": "@yourscope/mern-utils",
  "version": "1.0.0",
  "type": "module",
  "exports": "./src/index.js",
  "files": ["src"]
}

Note

Scope packages (@username/pkg) avoid name squatting. Semantic versioning: MAJOR.MINOR.PATCH.

Tip

Apply this in your Week 25 course project before moving on.

Performance

Mark sideEffects: false in package.json so bundlers can tree-shake your library.

Back to index


12. Testing and Maintaining Packages

Unit test public API surface. CI runs tests on every push. Changelog documents breaking changes.

Example:

javascript
// vitest or jest
import { slugify } from '../src/index.js'
test('slugify', () => {
  expect(slugify('Hello World')).toBe('hello-world')
})

Note

Use changesets or release-please for automated versioning in monorepos.

Tip

Apply this in your Week 25 course project before moving on.

Performance

Keep peerDependencies for frameworks (react, express) — avoid bundling them into your package.

Back to index


Week 26: Final Project & Career Paths

13. Final Package Project

Publish a utility package: slug generator, env validator, or Express middleware. Document with examples and TypeScript types.

Note

Quality README with install, usage, and API table matters more than feature count for adoption.

Tip

Apply this in your Week 26 course project before moving on.

Performance

Benchmark hot paths if your package is performance-critical (e.g., parsers, serializers).

Back to index


14. Node.js & Express Mastery Recap

Core review: event loop, modules, async patterns, middleware pipeline, security, testing, deployment.

  • Event loop — non-blocking I/O, avoid sync crypto on hot paths
  • Middleware order matters — parsers before routes, errors last
  • 12-factor app: config in env, logs to stdout, stateless processes

Tip

Apply this in your Week 26 course project before moving on.

Performance

Profile with clinic.js or --inspect before optimizing — measure, do not guess.

Back to index


15. MERN Career Paths & Portfolio

Roles: front-end, back-end, full-stack, DevOps. Showcase MERN projects on GitHub, write blog posts (like this series), contribute open source.

  • Portfolio: 2–3 deployed apps with README and live demos
  • Blog: explain what you built and tradeoffs you made
  • Network: local meetups, Twitter/X, LinkedIn, conference CFPs

Note

This portfolio site itself is a MERN-adjacent showcase — Next.js, MDX blog, Vercel deploy.

Tip

Apply this in your Week 26 course project before moving on.

Performance

Lighthouse scores and Core Web Vitals on portfolio pages signal front-end maturity to employers.

Back to index


Share this article

XLinkedInFacebook
Kazi Rahamatullah

Written by

Kazi Rahamatullah

FullStack Developer

X / TwitterGitHubLinkedIn

Subscribe to my newsletter

Stay up to date and get notified when I share new contents.

No spam ever, unsubscribe anytime