Appearance
Login in Express
40. How do you implement authentication and protect routes in Express?
The short answer
Split it into three parts. A login route checks the credentials and creates a session, or issues a token. An authentication middleware runs on protected routes, reads the session cookie or the Authorization header, verifies it, loads the user into req.user, and responds 401 if anything is missing or invalid. Authorization checks then decide what this user may do, with role middleware or checks inside the handler that respond 403. Mount the auth middleware on whole routers, so a new route is protected by default.
ts
// auth.ts
export async function requireUser(req: Request, res: Response, next: NextFunction) {
const userId = req.session.userId // (1)
if (!userId) return next(new HttpError(401, 'Sign in required'))
const user = await users.findById(userId)
if (!user || user.disabled) return next(new HttpError(401, 'Sign in required')) // (2)
req.user = user
next()
}
export const requireRole = (role: Role) => (req: Request, res: Response, next: NextFunction) =>
req.user?.roles.includes(role) ? next() : next(new HttpError(403, 'Not allowed')) // (3)
// app.ts
app.post('/auth/login', loginLimiter, loginHandler) // (4)
app.use('/api', requireUser) // (5)
app.use('/api/orders', ordersRouter)
app.use('/api/admin', requireRole('admin'), adminRouter) // (6)- Read the identity from the server-side session (express-session). With tokens, this line would verify a bearer JWT instead.
- Re-check the user exists and is active, so a disabled account stops working immediately, even with a valid session.
- A small factory that returns middleware for one role, responding
403for logged-in users without it. - Login is public, but rate limited (the rate limiting question).
- Everything under
/apineeds a user, so forgetting to protect a new route is impossible. - Admin routes need a role on top.
Typing req.user:
ts
declare global {
namespace Express {
interface Request { user?: User }
}
}Role checks are not enough for data. requireRole('customer') does not stop customer 7 from reading customer 9's order. Ownership checks live in the handler or the data layer: orders.findOne({ id, customerId: req.user.id }) (the authorization question).
41. What is Passport.js, and when is it useful?
The short answer
Passport is Express middleware that gives one common interface to many login methods, called strategies: passport-local for email and password, passport-google-oauth20, passport-openidconnect, passport-saml and hundreds more. Each strategy handles the protocol details and hands you a profile. Your verify callback finds or creates the user, and Passport stores the user in the session. It is useful when you need several login methods behind one shape. For a single OIDC provider, a dedicated OIDC client library is often simpler and more up to date.
ts
import passport from 'passport'
import { Strategy as LocalStrategy } from 'passport-local'
passport.use(new LocalStrategy({ usernameField: 'email' }, async (email, password, done) => { // (1)
try {
const user = await login(email, password) // (2)
done(null, user)
} catch {
done(null, false, { message: 'Invalid email or password' }) // (3)
}
}))
passport.serializeUser((user, done) => done(null, (user as User).id)) // (4)
passport.deserializeUser(async (id: string, done) => done(null, await users.findById(id))) // (5)
app.use(session(sessionOptions))
app.use(passport.session())
app.post('/auth/login', passport.authenticate('local', { failureMessage: true }), (req, res) => res.json({ ok: true }))- A strategy is configured once, with a
verifyfunction. - Your own credential check, with the slow hash and equal timing (the brute force question).
falsemeans "not authenticated", which Passport turns into a401.- Store only the user's ID in the session.
- Load the user from that ID on every request, into
req.user.
| Use Passport when | Skip it when |
|---|---|
| You need several login methods behind one interface | You use one OIDC provider: use its client library |
| You maintain an existing Passport app | You use a hosted login like Auth0 or Clerk with its own SDK |
| You need SAML in Express | You only issue API tokens |
Known traps. Passport version 0.6 and later regenerates the session at login to stop session fixation, and req.logout() now needs a callback. Many old tutorials are wrong on both. Also check that a strategy package is still maintained before you depend on it.
42. How does Google login work at a high level?
The short answer
"Sign in with Google" is OpenID Connect, which is the Authorization Code flow of OAuth 2.0 plus an ID token. Your site redirects the user to Google with your client ID, the scopes openid email profile, a state value and a PKCE challenge. The user signs in at Google and agrees. Google redirects back to your callback URL with a one-time code. Your server exchanges the code, plus your client secret and the PKCE verifier, for tokens. You verify the ID token, read the user's stable sub ID and email, find or create the user, and start your own session.
What your server checks before trusting the result:
statein the callback matches the one you saved in the session, which stops forged callbacks.- The ID token's signature, using Google's published keys.
issishttps://accounts.google.com, andaudis your own client ID.exphas not passed, and thenoncematches if you sent one.- Link by
sub, Google's permanent ID for the user, not by email. Only trustemailwhenemail_verifiedis true.
The full details of each step, and the code, are in the OAuth flows and OpenID Connect pages.