skip to content

In one Express codebase serving a session-based dashboard and a bearer-token mobile API, how do you wire Passport for both?

level: middleimportance: should knowfreq 45%

answer

  1. one instance, many strategies
  2. scope session support by router
  3. hooks only for the cookie side
  4. the API guard's extra option

basics

~10 s

Mount express-session and passport.session() only on the dashboard's router, register the sign-in strategy, the passport-jwt strategy and both serialization hooks once, and guard the API router with passport.authenticate('jwt', { session: false }).

solid answer

~40 s

Both halves share one `passport` instance and one user lookup. The dashboard router mounts express-session and `passport.session()`, so `serializeUser` runs at sign-in and `deserializeUser` rebuilds `req.user` on each page; its routes still check `req.isAuthenticated()`. The API router starts with `passport.authenticate('jwt', { session: false })`, so each call is checked from its bearer token, `req.user` lasts one request, and no session record or cookie is ever created. Scoping session middleware to the dashboard keeps API traffic from paying for session lookups. An API should skip sessions when its clients send a credential every time and do not keep cookies, as mobile apps and services do.

code

javascript · 34 lines
javascript
const express = require('express');
const session = require('express-session');
const passport = require('passport');
const { Strategy: JwtStrategy, ExtractJwt } = require('passport-jwt');

async function findUserById(id) {
  // one lookup shared by both halves; resolve undefined when absent
}
const toDone = (done) => (user) => done(null, user || false);

passport.use(new JwtStrategy({
  jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
  secretOrKey: process.env.JWT_PUBLIC_KEY,
  algorithms: ['RS256'],
}, (payload, done) => { findUserById(payload.sub).then(toDone(done), done); }));
passport.serializeUser((user, done) => done(null, user.id));
passport.deserializeUser((id, done) => { findUserById(id).then(toDone(done), done); });

const dashboard = express.Router();
dashboard.use(session({ secret: process.env.SESSION_SECRET, resave: false, saveUninitialized: false }));
dashboard.use(passport.session());
// ... the dashboard's sign-in and sign-out routes go here
dashboard.get('/', (req, res) => {
  if (!req.isAuthenticated()) return res.redirect('/dashboard/login');
  res.send(`Signed in as ${req.user.id}`);
});

const api = express.Router();
api.use(passport.authenticate('jwt', { session: false }));
api.get('/me', (req, res) => res.json({ id: req.user.id }));

const app = express();
app.use('/dashboard', dashboard);
app.use('/api', api);

go deeper

for a junior

Recall that the dashboard uses express-session with passport.session() and the API uses passport.authenticate('jwt', { session: false }).

for a middle

Explain why session support belongs on the dashboard router only, which hooks each half uses, and how long req.user lives on each side.

for a senior

Spot the strategy-array trap, the cost of app-wide session lookups, and how one forgotten option starts writing sessions for API clients.

for a principal

Decide which clients get sessions and which get tokens, and keep one user lookup so both halves revoke a disabled account the same way.

## One Passport, two ways in A single `passport` instance holds any number of strategies. In a codebase that serves both a **server-rendered dashboard** (browsers that keep a cookie) and a **mobile API** (clients that send a bearer token on every call), the two halves share that instance and the user lookup, and differ in two places: - the dashboard keeps login state in a server-side session, which needs express-session, `passport.session()` and the two serialization hooks; - the API keeps none, so its guard is `passport.authenticate('jwt', { session: false })`. ## The two halves side by side | | Dashboard | Mobile API | |---|---|---| | Credential on each request | Session cookie | `Authorization: Bearer <token>` | | Middleware | express-session, then `passport.session()` | `passport.authenticate('jwt', { session: false })` | | Hooks used | `serializeUser` at login, `deserializeUser` per request | Neither | | Lifetime of `req.user` | Rebuilt from the session on every request | The current request only | | Missing or bad credential | `req.user` unset; the route decides, often a redirect | 401 from Passport | | Server-side state | One session record per signed-in browser | None | ## Wiring it 1. Register the dashboard's sign-in strategy, the passport-jwt strategy and both serialization hooks once, at startup. 2. Create an `express.Router()` for the dashboard and mount express-session and `passport.session()` **on that router**, followed by its sign-in, sign-out and page routes. 3. Create a second router for the API and put `passport.authenticate('jwt', { session: false })` at its top, so every route below it is guarded and none can forget the option. 4. Mount the routers at their prefixes, for example `/dashboard` and `/api`. Scoping session support to the dashboard router means API traffic never loads or creates a session record and never pays for the deserializer's lookup. Mounting it app-wide also works, but then every API request performs a session lookup it ignores, and a single route missing `{ session: false }` starts writing a session record and a cookie for each API call. The express-session options themselves, its store and its cookie settings, are covered with session-store wiring. ## When an API should skip sessions Skip the session on an API when its clients: - send a credential with every call and do not keep cookies, as mobile apps and other services usually do; - carry a token another service issued, so there is no local sign-in to remember; - would otherwise force a shared session store across instances purely for their sake. A browser front end served from the same site is the usual case where a session may still fit better; which credential a browser should hold, and where, is a design question covered with token storage and transport. ## The API's own sign-in route If the API exchanges a username and password for a token itself, its credential route uses the same switch: `passport.authenticate('local', { session: false })` checks the credentials, Passport calls `req.login()` with `session` false so `req.user` is set for that request only, and the handler then issues the token in its response. Signing that token is the application's job, not Passport's. Leaving the option off here is the same mistake as on a guarded route: Passport would try to open a login session for a client that will never send the cookie back. ## Pitfalls - **A strategy array is not "either credential".** `passport.authenticate(['session', 'jwt'])` tries the strategies in order and stops at the first one that does not fail. The built-in `'session'` strategy never fails: it passes the request on, so a request with no login data reaches the handler with no `req.user`, and a valid bearer token on it is never even checked. - **Forgetting `{ session: false }`** on an API route makes Passport try to start a login session for the token's user. - **Restoring is not guarding.** `passport.session()` only restores the user; dashboard routes still have to check `req.isAuthenticated()` before rendering anything private. - **One user lookup, two callers.** Keep the lookup in one function both the deserializer and the JWT verify callback call, so the two halves cannot disagree about a disabled account.

  • How would you let one API route accept either the dashboard's session or a bearer token?
    Not with `passport.authenticate(['session', 'jwt'])`: the built-in session strategy passes instead of failing, so that chain lets an anonymous request through and never checks the token. Run `passport.session()` first, then a small middleware that calls `next()` when `req.isAuthenticated()` is true and otherwise calls `passport.authenticate('jwt', { session: false })(req, res, next)`. A cookie-authenticated API route also needs the dashboard's cross-site request protections.
  • Does the API half need express-session installed at all?
    No. With `{ session: false }` on its guard and no `passport.session()` in its chain, nothing on those routes reads or writes `req.session`. The package is there only because the dashboard needs it.

  • Two different passport instances are needed for sessions and tokens.
  • passport.authenticate(['session', 'jwt']) accepts a request carrying either credential and rejects the rest.
  • Mounting express-session app-wide is required for passport-jwt to work.
  • passport.session() blocks anonymous requests to the dashboard by itself.
  • With { session: false }, req.user persists until the token expires.