Examples: Auth & Sessions
These examples show how an Express application can combine request middleware with authentication state held in a session. The auth example builds an application with Express and express-session, while the session examples compare cookie-oriented and adapter-based session setups.
They exist to make the boundary between request handling and session persistence concrete: middleware decides whether a request may continue, while the selected session package determines where session state is represented. The acceptance test confirms that the cookie-session example returns a session cookie and observes state across requests.
Sources: examples/auth/index.js:10, examples/auth/index.js:12, examples/cookie-sessions/index.js:7, examples/session/index.js:11, examples/session/redis.js:9, examples/auth/index.js:75-82, test/acceptance/cookie-sessions.js:13-29
Core concepts
Authentication lookup
Authentication lookup checks a submitted name and password against the known user data and reports either a user or no user through a callback. In the example, authenticate looks up users[name], hashes the supplied password with the stored salt, and compares the resulting hash.
Sources: examples/auth/index.js:43-45, examples/auth/index.js:60-73
Route protection
Route protection is middleware that either passes the request onward or redirects an unauthenticated request to login. The example implements this policy in restrict by checking req.session.user.
Sources: examples/auth/index.js:75-82
Cookie-backed session
A cookie-backed session keeps the client-visible session representation involved in carrying state between requests. The cookie-sessions example imports cookie-session, and its acceptance test checks for a session cookie and reuses returned cookies to observe a changed visit count.
Sources: examples/cookie-sessions/index.js:7, test/acceptance/cookie-sessions.js:13-29
Redis-backed session
A Redis-backed session uses express-session together with a Redis store adapter rather than the cookie-session package. The Redis example imports RedisStore from connect-redis using the session module.
Sources: examples/session/redis.js:9, examples/session/redis.js:13
How the auth example protects a request
The auth example creates an Express application and loads express-session; it also loads hash, path, and the in-memory users data used by the authentication flow.
authenticate is the credential-checking step. It first obtains users[name]; a missing user immediately produces fn(null, null). For an existing user, it invokes hash with the submitted password and stored salt, then reports the user only when the computed hash matches.
The route guard is separate from credential verification. restrict reads req.session.user; when that value exists, it calls next(), handing control to the following handler. When it does not exist, it stores an error message in req.session.error and calls res.redirect('/login').
function restrict(req, res, next) {
if (req.session.user) {
next();
} else {
req.session.error = 'Access denied!';
res.redirect('/login');
}
}The important ordering is therefore: the request reaches restrict, an authenticated session continues through next(), and an unauthenticated session is redirected instead of reaching the downstream handler. The acceptance test verifies the observable unauthenticated result for GET /: a redirect to /login with status 302.
This is the custom-middleware hook for protecting a route before its later handler runs. The supplied auth excerpts do not show the route registration or a res.render call, so they establish the guard’s decision and hand-off behavior, but not the specific view-rendering statement that follows it.
The call order is summarized below; the two branches are the calls visible in restrict.
Evidence
- guardexamples/auth/index.js:75
- session-stateexamples/auth/index.js:75
- continuationexamples/auth/index.js:75
- login-responseexamples/auth/index.js:75
Sources: examples/auth/index.js:8, examples/auth/index.js:9, examples/auth/index.js:10, examples/auth/index.js:12, examples/auth/index.js:43-45, examples/auth/index.js:60-73, examples/auth/index.js:75-82, test/acceptance/auth.js:8-15
How session state is selected
The examples use different packages at the session boundary. The table separates the package imported by each example from the behavior directly verified by the supplied excerpts.
| Example | Session-related dependency | Evidence shown |
|---|---|---|
auth | session from express-session | The auth module imports the session package and reads req.session in restrict. |
cookie-sessions | cookieSession from cookie-session | The example imports cookie-session; acceptance tests observe a session cookie and revisit state. |
session | session from express-session | The example imports express-session. |
| redis.js | session plus RedisStore | The example imports express-session and connects RedisStore to it through connect-redis. |
The practical difference is visible in the evidence: cookie-sessions is tested through a returned cookie that is sent back on the next request, while redis.js introduces a store adapter alongside express-session. The excerpts do not show the complete session middleware configuration, so they do not establish the exact serialization format, Redis connection settings, or lifecycle of stored records.
The cookie-session acceptance flow makes the client round trip explicit. The first request receives Set-Cookie, and the second request sends the extracted cookie using set('Cookie', getCookies(res)); the response changes from viewed 1 times to viewed 2 times.
The Redis example shows the replacement seam for a different store: RedisStore is created by passing session to connect-redis. A different store would be plugged in at that adapter boundary, but the shown lines do not include the later registration that would attach the store to application middleware.
The package-level hand-offs are shown here.
Evidence
- cookie-exampleexamples/cookie-sessions/index.js:7
- cookie-packageexamples/cookie-sessions/index.js:7
- session-exampleexamples/session/index.js:11
- redis-exampleexamples/session/redis.js:9
- redis-exampleexamples/session/redis.js:13
- express-packageexamples/cookie-sessions/index.js:8
- express-packageexamples/session/redis.js:7
Sources: examples/auth/index.js:10, examples/auth/index.js:75-82, examples/cookie-sessions/index.js:7, examples/session/index.js:11, examples/session/redis.js:9, examples/session/redis.js:13, test/acceptance/cookie-sessions.js:13-29, examples/cookie-sessions/index.js:8
How it connects
The examples depend on Express application creation: app is initialized by calling express() in the auth, cookie-session, cookie, ordinary session, and Redis examples.
The auth guard connects session state to normal route dispatch through next() or res.redirect, so the surrounding routing and dispatch model is the next place to read for how handlers are registered and invoked. App Routing & Request Dispatch
The redirect branch connects to response behavior, while cookie handling connects to the response’s cookie and header helpers. Response: Headers, Cookies & Redirects
For the broader role of these programs as runnable examples and their acceptance coverage, continue with the examples overview and acceptance-test pages. Examples: Getting Started Acceptance Test Suite
Sources: examples/auth/index.js:12, examples/cookie-sessions/index.js:10, examples/cookies/index.js:8, examples/session/index.js:13, examples/session/redis.js:15, examples/auth/index.js:75-82
Key takeaways
restrictallows a request through withnext()only when req.session.user exists; otherwise it redirects to/login.authenticatehashes the submitted password with the stored salt and compares it with the stored hash.cookie-sessionsis verified through a returnedsessioncookie that preserves visit state across requests.- redis.js places
RedisStoreat theexpress-sessionintegration boundary.
Sources: examples/auth/index.js:75-82, examples/auth/index.js:60-73, examples/cookie-sessions/index.js:7, test/acceptance/cookie-sessions.js:13-29, examples/session/redis.js:9, examples/session/redis.js:13