ExpressJS Tutorial

Build fast and scalable Node.js backend applications

Backend Fundamentals API Development Production Ready

Table of Contents

What is Express.js?

Express.js is a minimal and flexible Node.js web application framework that provides a robust set of features for building web and mobile applications. It's essentially a layer built on top of Node.js that simplifies handling HTTP requests, routing, middleware integration, and more.

Key Characteristics

Unopinionated

Doesn't force you into specific patterns.

Minimalistic

Lightweight with core features only.

Flexible

Easily extendable with middleware.

Fast

Minimal overhead on top of Node.js.

Built on Node.js

Express.js harnesses the power of Node.js's event-driven, non-blocking I/O model, making it ideal for building high-performance web applications and APIs.

Why Use Express.js?

Without Express (Raw Node.js)

JavaScriptconst http = require('http'); const server = http.createServer((req, res) => { if (req.url === '/' && req.method === 'GET') { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('Home Page'); } else if (req.url === '/users' && req.method === 'GET') { res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ users: ['Alice', 'Bob'] })); } else { res.writeHead(404); res.end('Not Found'); } }); server.listen(3000);

With Express.js

JavaScriptconst express = require('express'); const app = express(); app.get('/', (req, res) => res.send('Home Page')); app.get('/users', (req, res) => res.json({ users: ['Alice', 'Bob'] })); app.listen(3000);

Advantages of Express.js

Feature Benefit
Simplified RoutingClean, intuitive API for route definitions
Middleware SupportEasy to add functionality like logging, auth, compression
Template IntegrationSeamless integration with template engines
Robust APIBuilt-in methods for common tasks
Large EcosystemThousands of middleware packages available
Active CommunityExtensive documentation and support
Production ReadyUsed by companies like Uber, IBM, Netflix

Prerequisites

Before starting with Express.js, ensure you have:

Technical Requirements

  • Node.js (v12 or higher) installed
  • npm (Node Package Manager) included with Node.js
  • Basic knowledge of JavaScript (ES6+)
  • Understanding of Node.js fundamentals (modules, file system, etc.)
  • Familiarity with HTTP concepts (methods, status codes, headers)

Check Your Setup

Bash# Check Node.js version node --version # Check npm version npm --version

Project Structure (Simple)

Folder Structureexpress-intro/ ├── node_modules/ ├── package.json ├── package-lock.json └── app.js (or server.js)

Recommended Packages for Production

Bashnpm install dotenv # Environment variables npm install winston # Logging npm install mongoose # MongoDB ODM npm install jsonwebtoken # JWT authentication npm install bcryptjs # Password hashing npm install cors # CORS support npm install express-validator # Input validation npm install nodemon --save-dev # Auto-restart during development

Key Features

Routing System

Define clean URL endpoints for GET, POST, PUT, DELETE, and more.

Middleware Pipeline

Run request processing logic step-by-step for auth, logs, validation, and parsing.

Template Engine Support

Render dynamic views using EJS, Pug, Handlebars, and other engines.

REST API Friendly

Perfect for building scalable API backends for mobile and frontend apps.

ExpressJS Architecture

Express follows a middleware-driven request/response cycle.

  1. Client sends an HTTP request.
  2. Express receives the request and passes it through middleware functions.
  3. Routing layer matches the path and method.
  4. Controller/business logic processes data and optional database operations.
  5. Response is returned as JSON, HTML, or another format.

Express.js MCQ Practice

10 Basic MCQs 10 Advanced MCQs

10 Basic Express.js MCQs

1

What is Express.js built on top of?

AReact
BNode.js
CPython
DPHP
Explanation: Express.js is a minimal web framework for Node.js.
2

Which function creates an Express application instance?

AcreateApp()
Bexpress()
Cnew Express()
Dserver()
Explanation: const app = express(); is the standard way to initialize Express.
3

Which HTTP method does app.get() handle?

AGET
BPOST
CPUT
DDELETE
Explanation: app.get() defines routes for GET requests.
4

What is middleware in Express?

AA database model
BFunctions that process requests in the pipeline
CA template engine
DA CSS preprocessor
Explanation: Middleware runs between request and response for logging, auth, parsing, etc.
5

Which method sends a JSON response?

Ares.sendJson()
Bres.json()
Cres.write()
Dres.text()
Explanation: res.json() sets Content-Type and sends JSON data.
6

What does express.json() middleware parse?

AURL query strings
BHTML forms only
CJSON request bodies
DStatic files
Explanation: Built-in middleware parses incoming JSON payloads into req.body.
7

Where are route parameters like /users/:id accessed?

Areq.query
Breq.params
Creq.body
Dreq.headers
Explanation: Named route segments are available on req.params.
8

Query string values like ?page=2 are found in:

Areq.params
Breq.route
Creq.query
Dreq.path
Explanation: Query parameters are parsed into req.query.
9

Which command installs Express in a project?

Anpm install express
Bnode install express
Cexpress init
Dnpm get express
Explanation: Express is installed as an npm package with npm install express.
10

Which method starts the Express server?

Aapp.start()
Bapp.run()
Capp.listen()
Dserver.boot()
Explanation: app.listen(port, callback) binds and listens for connections.

10 Advanced Express.js MCQs

1

What does calling next() do in middleware?

AEnds the response immediately
BPasses control to the next middleware
CRestarts the server
DSkips all remaining routes
Explanation: next() continues the middleware chain unless a response is already sent.
2

How many arguments does Express error-handling middleware require?

A2
B3
C4 (err, req, res, next)
D5
Explanation: Error middleware is recognized by its 4-parameter signature.
3

Which creates a modular mini-application for grouped routes?

Aexpress.Module()
Bexpress.Router()
Capp.routeGroup()
Dexpress.Controller()
Explanation: Routers help organize routes into separate files/modules.
4

Main difference between app.use() and app.get()?

Aapp.use() only handles POST
Bapp.use() mounts middleware for all HTTP methods on a path
Capp.get() runs middleware only
DThere is no difference
Explanation: app.use() is method-agnostic and often used for middleware mounting.
5

Which status code should be returned after successfully creating a resource?

A200
B201
C204
D301
Explanation: REST APIs commonly use 201 Created for successful POST creation.
6

What is the purpose of the Helmet middleware?

ASet secure HTTP headers
BCompress responses
CParse cookies
DConnect to MongoDB
Explanation: Helmet helps secure apps by setting various HTTP headers.
7

What does the CORS middleware enable?

AServer-side rendering
BCross-origin requests from browsers
CDatabase migrations
DFile encryption
Explanation: CORS controls which origins can access your API from the browser.
8

Which middleware serves static files like CSS and images?

Aexpress.static()
Bexpress.files()
Cexpress.assets()
Dexpress.public()
Explanation: express.static('public') serves files from a directory.
9

Why use process.env.PORT in production deployments?

AHosting platforms assign the port dynamically
BIt disables HTTPS
CIt enables cluster mode automatically
DIt replaces environment variables
Explanation: PaaS providers like Render/Railway inject PORT at runtime.
10

Best practice for handling errors in async route handlers?

AIgnore errors silently
BUse try/catch and pass errors to next(err)
CAlways return HTML error pages only
DRestart Node on every error
Explanation: Forwarding errors to Express error middleware keeps API responses consistent.

15 Interview Questions & Answers

Easy Medium Hard
1What is Express.js?easy
Answer: Express.js is a fast, minimalist web framework for Node.js that simplifies routing, middleware, and HTTP request/response handling for APIs and web apps.
2What is the difference between req.params and req.query?easy
Answer: req.params holds route path parameters (e.g. /users/:id), while req.query holds URL query string values (e.g. ?page=2&limit=10).
3What is middleware in Express?easy
Answer: Middleware functions have access to req, res, and next. They run in order during the request-response cycle for tasks like parsing, logging, authentication, and validation.
4How do you parse JSON request bodies?easy
Answer: Use built-in middleware: app.use(express.json()). Parsed data is available on req.body.
5How do you serve static files in Express?easy
Answer: Mount static middleware: app.use('/static', express.static('public')). Express serves files from the specified folder.
6What is express.Router() used for?medium
Answer: It creates modular route handlers that can be mounted on the main app (e.g. app.use('/api/users', userRouter)), improving code organization and maintainability.
7How does Express error-handling middleware work?medium
Answer: Error middleware is defined with four parameters: (err, req, res, next). Express recognizes this signature and routes errors thrown or passed via next(err) to it.
8What is the difference between app.use() and app.get()?medium
Answer: app.get() handles GET requests for a specific path. app.use() mounts middleware for all HTTP methods on a path prefix and is commonly used for shared logic.
9What is CORS and why is it needed in Express APIs?medium
Answer: Cross-Origin Resource Sharing controls which domains can access your API from browsers. Without CORS headers, frontend apps on different origins are blocked by browser security policies.
10How do you implement JWT authentication in Express?medium
Answer: On login, verify credentials and issue a signed JWT. Protect routes with auth middleware that validates the token from the Authorization header and attaches user data to req.user.
11What are RESTful routing conventions in Express?medium
Answer: Use resource-based URLs and HTTP verbs: GET /users (list), GET /users/:id (read), POST /users (create), PUT/PATCH /users/:id (update), DELETE /users/:id (delete).
12What is rate limiting and why use it?medium
Answer: Rate limiting restricts requests per IP/user within a time window. It prevents abuse, brute-force attacks, and protects server resources from traffic spikes.
13How do you handle async errors in route handlers?hard
Answer: Wrap async handlers with try/catch and call next(err), or use an async wrapper utility that forwards rejected promises to Express error middleware automatically.
14What is the N+1 query problem and how do you avoid it in APIs?hard
Answer: N+1 occurs when you fetch a list (1 query) then run a separate query for each item (N queries). Fix it with JOINs, eager loading (include in Prisma), or batch queries.
15What are key security best practices for Express in production?hard
Answer: Use Helmet for security headers, validate/sanitize input, parameterized queries, HTTPS, rate limiting, secure JWT/session secrets, CORS restrictions, dependency updates, and centralized error handling without leaking stack traces.