Other Examples
This page documents the additional example applications included in the Express repository. These examples demonstrate authentication, content negotiation, sessions, error handling, and other common Express patterns. Each example is a self-contained application in its own subdirectory under examples/.
Authentication Example (examples/auth)
Purpose: Demonstrates user authentication with session management, including login, logout, and restricted access to protected routes.
Key files:
examples/auth/index.js, Main application entry point
How authentication works:
The example uses a placeholder database stored in memory as a plain object:
var users = {
tj: { name: 'tj' }
};When the application starts, it generates a salt and hash for the password 'foobar' using the pbkdf2-password module:
hash({ password: 'foobar' }, function (err, pass, salt, hash) {
if (err) throw err;
users.tj.salt = salt;
users.tj.hash = hash;
});The authenticate function (lines 60-73) compares the provided password against the stored hash:
function authenticate(name, pass, fn) {
if (!module.parent) console.log('authenticating %s:%s', name, pass);
var user = users[name];
if (!user) return fn(null, null)
hash({ password: pass, salt: user.salt }, function (err, pass, salt, hash) {
if (err) return fn(err);
if (hash === user.hash) return fn(null, user)
fn(null, null)
});
}Session management flow:
-
Login POST (
/login): The application callsauthenticate(). On success, it regenerates the session to prevent session fixation attacks usingreq.session.regenerate(), then stores the user object inreq.session.user. On failure, it setsreq.session.errorand redirects back to the login page. -
Restricted access: The
restrictmiddleware (lines 75-82) checksreq.session.user. If absent, it sets an error message and redirects to/login:
function restrict(req, res, next) {
if (req.session.user) {
next();
} else {
req.session.error = 'Access denied!';
res.redirect('/login');
}
}- Logout (
/logout): Destroys the session usingreq.session.destroy()and redirects to the root.
Session-persisted message middleware: A custom middleware (lines 27-36) reads req.session.error and req.session.success messages, stores them in res.locals.message for rendering, then deletes them from the session. This implements a flash message pattern.
Public API:
| Symbol | Signature | Purpose |
|---|---|---|
authenticate | function(name, pass, fn) | Validates username/password against the in-memory database |
restrict | function(req, res, next) | Middleware that blocks unauthenticated access |
Content Negotiation Example (examples/content-negotiation)
Purpose: Demonstrates how Express responds with different content types (HTML, text, JSON) based on the request's Accept header.
Key files:
examples/content-negotiation/index.js, Main application entry pointexamples/content-negotiation/db.js, In-memory user data storeexamples/content-negotiation/users.js, Response handlers for each content type
How content negotiation works:
The example uses a declarative route format with a helper function. The format function (line 33-38) maps content types to handler functions:
function format(obj) {
return function(req, res, next) {
for (var key in obj) {
if (req.accepts(key)) {
return obj[key](req, res, next);
}
}
// default to first key
obj[Object.keys(obj)[0]](req, res, next);
};
}This function iterates over the provided object keys, checking each content type against the request's Accept header using req.accepts(). If a match is found, the corresponding handler is called. If no match is found, it falls back to the first handler.
The users.js file exports three handlers, html, text, and json, each rendering or sending the user list in the appropriate format.
Public API (from users.js):
| Symbol | Purpose |
|---|---|
html | Renders an HTML view of the users list |
text | Sends a plain text representation |
json | Sends a JSON representation |
Session Examples
Basic Session (examples/session)
Purpose: Demonstrates session-based page view counting using the express-session middleware.
Key files:
examples/session/index.js, Main application entry point
The application increments req.session.views on each request and displays the count to the user. This is the simplest demonstration of session state persistence across requests.
Redis Session Storage (examples/session/redis)
Purpose: Demonstrates using Redis as a session store via the connect-redis module.
Key files:
examples/session/redis.js, Main application entry point
This example extends the basic session pattern by configuring express-session with a Redis store, showing how to scale sessions across multiple server instances.
Cookie Sessions (examples/cookie-sessions)
Purpose: Demonstrates cookie-based sessions using the cookie-session middleware.
Key files:
examples/cookie-sessions/index.js, Main application entry point
Unlike server-side session storage, cookie sessions store the session data directly in the cookie (signed for integrity). This example tracks page views without requiring a server-side store.
Error Handling Examples
Basic Error Handling (examples/error)
Purpose: Demonstrates error-handling middleware with arity 4 (four parameters) that catches errors thrown in route handlers or passed to next().
Key files:
examples/error/index.js, Main application entry point
The error handler function (lines 20-27) receives err, req, res, and next parameters:
function error(err, req, res, next) {
// logic as shown in the source
}This example shows two patterns for triggering errors: throwing an Error object inside a route handler, and passing an error to next(err).
Custom Error Pages (examples/error-pages)
Purpose: Demonstrates custom error pages for 404, 403, and 500 status codes with content negotiation and verbose error settings.
Key files:
examples/error-pages/index.js, Main application entry point
This example defines separate middleware for each error type, rendering appropriate views. It also enables app.set('verbose errors', true) to show detailed error information in development.
Additional Examples
Cookies (examples/cookies)
Purpose: Demonstrates reading and writing signed cookies with cookie-parser, including a "remember me" checkbox.
Key files:
examples/cookies/index.js, Main application entry point
Downloads (examples/downloads)
Purpose: Demonstrates file downloads using res.download() with a dynamic route and error handling for missing files.
Key files:
examples/downloads/index.js, Main application entry point
Hello World (examples/hello-world)
Purpose: Minimal Express application that responds with "Hello World" on GET /.
Key files:
examples/hello-world/index.js, Main application entry point
Markdown View Engine (examples/markdown)
Purpose: Registers .md as a view engine using the marked module, rendering Markdown files with template variable substitution.
Key files:
examples/markdown/index.js, Main application entry point
Multi-Router (examples/multi-router)
Purpose: Mounts two API routers under /api/v1 and /api/v2, demonstrating multi-router usage for API versioning.
Key files:
examples/multi-router/index.js, Main application entry pointexamples/multi-router/controllers/api_v1.js, API v1 routesexamples/multi-router/controllers/api_v2.js, API v2 routes
Online Users (examples/online)
Purpose: Tracks online users using Redis and the online module, displaying the last 5 active user agents.
Key files:
examples/online/index.js, Main application entry point
The list function (lines 40-44) retrieves and displays the most recent online users.
Route Parameters (examples/params)
Purpose: Demonstrates app.param() to convert route parameters to integers and load user objects from a faux database.
Key files:
examples/params/index.js, Main application entry point
Resource Routing (examples/resource)
Purpose: Demonstrates a custom app.resource() method to define RESTful routes for a resource, including index, show, destroy, and range.
Key files:
examples/resource/index.js, Main application entry point
Route Map (examples/route-map)
Purpose: Demonstrates a declarative route mapping using an object structure to define routes and handlers.
Key files:
examples/route-map/index.js, Main application entry point
Route Middleware (examples/route-middleware)
Purpose: Demonstrates route-specific middleware for loading a user, restricting access to self, and restricting by role.
Key files:
examples/route-middleware/index.js, Main application entry point
Public API:
| Symbol | Signature | Purpose |
|---|---|---|
loadUser | function(req, res, next) | Loads user object from faux database by ID |
andRestrictToSelf | function(req, res, next) | Restricts access to the authenticated user only |
andRestrictTo | function(role) | Returns middleware that restricts access to a specific role |
Redis Search (examples/search)
Purpose: Demonstrates a Redis-backed search endpoint that returns set members for a given query, with an async initialization.
Key files:
examples/search/index.js, Main application entry pointexamples/search/public/client.js, Client-side XHR searchexamples/search/public/index.html, Search page HTML
The initializeRedis function (lines 29-46) populates Redis with sample data on startup.
Static Files (examples/static-files)
Purpose: Demonstrates serving static files from multiple directories using express.static() with and without a mount path.
Key files:
examples/static-files/index.js, Main application entry pointexamples/static-files/public/css/style.css, Empty CSS fileexamples/static-files/public/js/app.js, Placeholder JavaScript file
Virtual Hosting (examples/vhost)
Purpose: Demonstrates virtual hosting using the vhost middleware, with a main app and a redirect app for subdomains.
Key files:
examples/vhost/index.js, Main application entry point
Custom View Constructor (examples/view-constructor)
Purpose: Demonstrates using a custom view constructor (GithubView) to render Markdown templates from a GitHub repository.
Key files:
examples/view-constructor/index.js, Main application entry pointexamples/view-constructor/github-view.js, Custom view constructor
The GithubView class (lines 23-30) fetches templates from GitHub via HTTPS and renders them using the registered engine.
View Locals (examples/view-locals)
Purpose: Demonstrates different patterns for passing locals to views: nested callbacks, middleware with req, and middleware with res.locals.
Key files:
examples/view-locals/index.js, Main application entry pointexamples/view-locals/user.js, Faux User model
Public API (from user.js):
| Symbol | Purpose |
|---|---|
User | Faux model with async all() and count() methods |
Web Service (examples/web-service)
Purpose: Demonstrates a simple RESTful web service with API key validation, returning JSON for users and repos.
Key files:
examples/web-service/index.js, Main application entry point
The error function (lines 15-19) handles API errors with appropriate status codes and JSON responses.
Comparison and Relationships
The examples demonstrate a progression of Express concepts:
| Concept | Examples | Key Takeaway |
|---|---|---|
| Basic routing | hello-world, route-map, resource | Different ways to define routes |
| Middleware patterns | route-middleware, error, error-pages | How to compose middleware chains |
| Session management | session, session/redis, cookie-sessions, auth | Client-side vs server-side sessions |
| Authentication | auth | Password hashing, session regeneration, restricted routes |
| Content negotiation | content-negotiation, error-pages | Responding with appropriate content types |
| View engines | markdown, view-constructor, view-locals | Custom engines and template variables |
| External storage | session/redis, online, search | Redis integration patterns |
| API design | multi-router, web-service, resource | Versioning, RESTful patterns, key validation |
| Static assets | static-files, downloads | File serving and download patterns |
The authentication example (auth) builds on the session example by adding password hashing and session regeneration. The error handling examples (error, error-pages) show both basic and advanced error patterns. The content negotiation example demonstrates a pattern used by error-pages for serving error pages in multiple formats.