๐ ExpressJS ยท subject
ExpressJS Core Concepts of ExpressJS Syllabus
The Core Concepts of ExpressJS syllabus for ExpressJS in full: 4 chapters and 16 topics, every one listed below, plus 51 Core Concepts of ExpressJS flashcards with answers.
Core Concepts of ExpressJS syllabus: all 4 chapters
Expand any chapter to see its topics and sub-topics.
-
Middleware
4 topics- What is Middleware?
- Built-in Middleware
- Third-party Middleware
- Custom Middleware
-
Routing
5 topics- Defining Routes
- Route Methods
- Route Parameters
- Route Handlers
- Express Router
-
Request and Response Objects
4 topics- Understanding req Object
- Understanding res Object
- Handling Different Content Types
- Sending Responses
-
Error Handling
3 topics- Built-in Error Handling
- Custom Error Handling Middleware
- Debugging Tips
ExpressJS Core Concepts of ExpressJS flashcards โ 51 questions with answers
What is middleware in Express.js?
Middleware are functions that have access to the request object (req), the response object (res), and the next middleware function in the application's request-response cycle. They can execute code, modify req/res, end the cycle, or call next() to pass control onward.
What is the standard signature of an Express middleware function?
function(req, res, next) { ... } โ it receives the request object, the response object, and the next function. Error-handling middleware uses four arguments: (err, req, res, next).
What are the main types of middleware in Express?
Application-level, router-level, error-handling, built-in, and third-party middleware.
What happens if a middleware neither ends the request nor calls next()?
The request hangs โ it is left pending because control is never passed on and no response is sent, so the client eventually times out.
How is middleware attached at the application level in Express?
Using app.use() (runs for every request or a path) or a method like app.get()/app.post() bound to a specific route and HTTP verb.
Does middleware execution order matter in Express?
Yes. Middleware runs in the exact order it is defined with app.use()/app.METHOD(). A middleware only affects requests reaching it, so ordering determines behavior (e.g., body parsers must run before route handlers that read req.body).
What is built-in middleware in Express?
Middleware that ships with Express itself and requires no separate install, such as express.json(), express.urlencoded(), express.static(), and express.text()/express.raw().
What does express.json() do?
It is built-in middleware that parses incoming requests with JSON payloads and populates req.body with the resulting JavaScript object.
What does express.urlencoded() do and what is the extended option?
It parses URL-encoded form bodies (Content-Type: application/x-www-form-urlencoded) into req.body. extended: true uses the qs library allowing nested/rich objects; extended: false uses the querystring library allowing only simple key-value pairs.
What does express.static() do?
It is built-in middleware that serves static files (HTML, images, CSS, JS) from a specified directory, e.g. app.use(express.static('public')).
What is third-party middleware and how is it added?
Middleware written outside Express, installed via npm (e.g., npm install morgan) and then loaded with require() and mounted using app.use(). Examples: morgan, cors, helmet, cookie-parser, express-session.
Name three common third-party middleware packages and their purpose.
morgan โ HTTP request logging; cors โ enabling Cross-Origin Resource Sharing; helmet โ setting security-related HTTP headers. (Others: cookie-parser, express-session, multer.)
What is custom middleware and how do you write one?
A user-defined function with signature (req, res, next) that performs some logic (logging, auth, validation) and then calls next(). Example: const logger = (req, res, next) => { console.log(req.method, req.url); next(); }; app.use(logger);
How do you restrict a custom middleware to only run for a specific path?
Pass the path as the first argument to app.use(), e.g. app.use('/admin', authMiddleware) โ the middleware then runs only for requests whose path starts with /admin.
What is the difference between built-in, third-party, and custom middleware?
Built-in ships with Express (express.json, express.static); third-party is installed from npm (morgan, cors); custom is written by the developer for app-specific logic. All share the (req, res, next) signature.
How do you define a basic route in Express?
Using app.METHOD(path, handler), e.g. app.get('/users', (req, res) => res.send('Users')). METHOD is the lowercase HTTP verb, path is the route pattern, and handler is the callback executed when the route matches.
What are the anatomy/components of an Express route?
A route consists of an HTTP method (verb), a path (URL pattern), and one or more handler functions executed when the request matches both the method and the path.
What are Express route methods and which HTTP verbs do they correspond to?
Methods on the app/router that map to HTTP verbs: app.get, app.post, app.put, app.delete, app.patch, app.head, app.options, etc. Each responds only to requests using that verb on the matching path.
What does app.all() do?
It defines a route handler that responds to all HTTP methods for a given path, useful for middleware-style logic that must run regardless of verb, e.g. app.all('/secret', requireAuth).
What are route parameters in Express and how are they defined?
Named URL segments prefixed with a colon that capture values at their position, defined like /users/:id. The captured values are available on req.params, e.g. req.params.id.
Show the other 31 Core Concepts of ExpressJS flashcards
How do you access multiple route parameters, e.g. /users/:userId/books/:bookId?
Through the req.params object: req.params.userId and req.params.bookId. Each named segment becomes a property on req.params.
What is the difference between route parameters and query parameters in Express?
Route parameters are part of the URL path (/users/:id โ req.params) and are typically required; query parameters follow a ? in the URL (/users?sort=asc โ req.query) and are typically optional filters.
What is a route handler in Express?
A callback function (with signature (req, res) or (req, res, next)) that executes when a route matches, responsible for processing the request and sending a response.
Can a single route have multiple handlers, and how do they chain?
Yes. You can pass multiple handler functions (or an array) to a route, e.g. app.get('/x', h1, h2, h3). Each handler must call next() to pass control to the next handler in the chain; otherwise the chain stops.
What is the Express Router?
An isolated, mini application instance created with express.Router() that groups related routes and middleware into a modular, mountable unit, which is attached to the main app via app.use().
How do you create and mount an Express Router?
const router = express.Router(); define routes like router.get('/', handler); then mount with app.use('/base', router). Requests to /base + route path are handled by that router.
What are the benefits of using express.Router()?
Modular organization of routes, ability to apply router-level middleware to a group, cleaner separation into files, and reusable path prefixes via mounting.
What is the req object in Express?
The HTTP request object representing the incoming request; it exposes properties and methods for reading the request such as req.params, req.query, req.body, req.headers, req.method, req.path, and req.cookies.
What do req.params, req.query, and req.body each contain?
req.params โ route/path parameters (:id); req.query โ parsed URL query string parameters (?key=value); req.body โ the parsed request payload (requires a body-parsing middleware like express.json()).
How do you read a request header in Express?
Using req.get('Header-Name') (case-insensitive) or the req.headers object, e.g. req.get('Content-Type') or req.headers['content-type'].
What is the res object in Express?
The HTTP response object used to build and send the reply to the client; it exposes methods like res.send(), res.json(), res.status(), res.redirect(), res.sendFile(), and res.set()/res.append().
What is the difference between res.send() and res.json()?
res.send() sends a response of various types (string, Buffer, object, array) and infers the Content-Type; res.json() explicitly serializes the argument to JSON and sets Content-Type to application/json. res.json() also correctly handles values like null.
How do you set the HTTP status code of a response in Express?
With res.status(code), which is chainable, e.g. res.status(404).send('Not Found') or res.status(201).json(data).
What does res.redirect() do?
It sends a redirect response to the client, setting the Location header and a 3xx status (302 by default). Example: res.redirect('/login') or res.redirect(301, '/new-url').
How does Express handle different content types when receiving requests?
By using the appropriate body-parsing middleware matched to the request's Content-Type: express.json() for application/json, express.urlencoded() for form data, express.text() for text/plain, and express.raw() for binary/Buffer bodies.
How do you explicitly set the response Content-Type in Express?
Using res.type('...') or res.set('Content-Type', '...'), e.g. res.type('html') or res.set('Content-Type', 'application/xml').
What is content negotiation and how does res.format() support it?
Content negotiation serves different representations based on the client's Accept header. res.format() lets you define handlers per content type, e.g. res.format({ 'text/html': ()=>..., 'application/json': ()=>... }), and Express picks the best match.
List the main methods used to send responses in Express.
res.send() (generic), res.json() (JSON), res.sendFile() (a file), res.render() (a view/template), res.redirect() (redirect), res.end() (end without data), and res.download() (prompt file download).
Why can you only send one response per request in Express?
Because a response method (res.send/json/end) ends the response and writes headers/body; calling another afterward triggers the 'Cannot set headers after they are sent to the client' error since the HTTP response is already committed.
What does res.sendStatus() do?
It sets the response HTTP status code and sends its standard message text as the body in one call, e.g. res.sendStatus(200) sends 'OK', res.sendStatus(404) sends 'Not Found'.
What is Express's default (built-in) error handling behavior?
Express ships with a built-in default error handler. Errors thrown in synchronous code or passed to next(err) are caught and by default sent to the client with a stack trace in development, and a generic message plus 500 status in production.
How do you forward an error to Express's error-handling middleware?
By passing the error to next(), i.e. next(err). Any truthy value passed to next() (other than the string 'route') tells Express to skip remaining normal middleware and invoke error-handling middleware.
How does Express handle errors thrown in asynchronous code (e.g., in a Promise)?
In Express 4, async errors are NOT caught automatically โ you must catch them and call next(err) yourself (or use a wrapper). In Express 5, rejected promises returned from handlers are automatically forwarded to error middleware.
What distinguishes an error-handling middleware function in Express?
It has exactly four arguments: (err, req, res, next). Express identifies error handlers by this arity and only calls them when an error is passed to next().
Write a basic custom error-handling middleware.
app.use((err, req, res, next) => { console.error(err.stack); res.status(err.status || 500).json({ error: err.message }); }); It must be defined after all other app.use() and routes.
Where must error-handling middleware be placed in the middleware stack?
Last โ after all other app.use() calls and route definitions โ so that errors from earlier middleware/routes propagate down to it.
How do you handle 404 (route not found) errors in Express?
Add a catch-all middleware after all routes, e.g. app.use((req, res) => res.status(404).send('Not Found')); it runs when no earlier route matched the request.
How can you set a custom status code on an error passed to next()?
Attach a property to the error object, e.g. const err = new Error('Forbidden'); err.status = 403; next(err); then read err.status in the error handler to call res.status(err.status).
What is the DEBUG environment variable used for in Express?
It enables Express's internal debug logging via the debug module. Setting DEBUG=express:* (e.g. DEBUG=express:* node app.js) prints detailed logs of routing and middleware execution to help diagnose issues.
What are effective debugging tips for an Express application?
Use DEBUG=express:* for internal logs; add request-logging middleware like morgan; use console.log or the Node inspector (node --inspect) with breakpoints; check middleware order; and always include an error-handling middleware to surface stack traces.
Why is a hanging (never-responding) request often a middleware bug, and how do you debug it?
It usually means a middleware neither sent a response nor called next(), so the chain stalls. Debug by logging entry/exit of each middleware to find where control stops, and ensure every non-terminal middleware calls next().
ExpressJS Core Concepts of ExpressJS FAQ
What is in the ExpressJS Core Concepts of ExpressJS syllabus?
ExpressJS Core Concepts of ExpressJS is split into 4 chapters: Middleware, Routing, Request and Response Objects and Error Handling. Together they contain 16 topics.
How many chapters are in ExpressJS Core Concepts of ExpressJS?
4 chapters, containing 16 topics. The largest chapter is Routing, with 5 topics.
Are there flashcards for ExpressJS Core Concepts of ExpressJS?
Yes โ a 51-card Core Concepts of ExpressJS deck, printed in full in the flashcards section of this page and available in the Examius app with spaced repetition. The free plan covers one exam of your choice, including its flashcards; Examius Pro, a one-time purchase, unlocks every other exam and deck.