0
0
ExpressHow-ToBeginner · 4 min read

How to Implement OAuth in Express: Simple Guide with Example

To implement OAuth in Express, use the passport library with an OAuth strategy like passport-google-oauth20. Configure Passport with client credentials, set up routes for login and callback, and use middleware to protect routes after authentication.
📐

Syntax

Implementing OAuth in Express involves these parts:

  • passport: Middleware to handle authentication.
  • OAuth Strategy: Specific provider strategy like Google or GitHub.
  • Routes: For login and callback URLs.
  • Session: To keep user logged in.
javascript
import express from 'express';
import passport from 'passport';
import { Strategy as GoogleStrategy } from 'passport-google-oauth20';

passport.use(new GoogleStrategy({
  clientID: 'YOUR_CLIENT_ID',
  clientSecret: 'YOUR_CLIENT_SECRET',
  callbackURL: '/auth/google/callback'
}, (accessToken, refreshToken, profile, done) => {
  // User profile processing
  done(null, profile);
}));

passport.serializeUser((user, done) => done(null, user));
passport.deserializeUser((obj, done) => done(null, obj));

const app = express();
app.use(require('express-session')({ secret: 'secret', resave: false, saveUninitialized: true }));
app.use(passport.initialize());
app.use(passport.session());

app.get('/auth/google', passport.authenticate('google', { scope: ['profile'] }));
app.get('/auth/google/callback', passport.authenticate('google', { failureRedirect: '/' }), (req, res) => {
  res.redirect('/protected');
});

app.get('/protected', (req, res) => {
  if (!req.isAuthenticated()) return res.redirect('/');
  res.send('Protected content for ' + req.user.displayName);
});
💻

Example

This example shows a simple Express app using Passport with Google OAuth 2.0. It lets users log in with Google and access a protected page showing their name.

javascript
import express from 'express';
import session from 'express-session';
import passport from 'passport';
import { Strategy as GoogleStrategy } from 'passport-google-oauth20';

const app = express();

passport.use(new GoogleStrategy({
  clientID: 'YOUR_CLIENT_ID',
  clientSecret: 'YOUR_CLIENT_SECRET',
  callbackURL: '/auth/google/callback'
}, (accessToken, refreshToken, profile, done) => {
  done(null, profile);
}));

passport.serializeUser((user, done) => done(null, user));
passport.deserializeUser((obj, done) => done(null, obj));

app.use(session({ secret: 'secret', resave: false, saveUninitialized: true }));
app.use(passport.initialize());
app.use(passport.session());

app.get('/', (req, res) => {
  res.send('<a href="/auth/google">Log in with Google</a>');
});

app.get('/auth/google', passport.authenticate('google', { scope: ['profile'] }));

app.get('/auth/google/callback', passport.authenticate('google', { failureRedirect: '/' }), (req, res) => {
  res.redirect('/protected');
});

app.get('/protected', (req, res) => {
  if (!req.isAuthenticated()) return res.redirect('/');
  res.send(`<h1>Hello, ${req.user.displayName}</h1><p>This is protected content.</p>`);
});

app.listen(3000, () => console.log('Server running on http://localhost:3000'));
Output
Server running on http://localhost:3000
⚠️

Common Pitfalls

  • Forgetting to set up express-session causes authentication to fail because sessions are needed to track login state.
  • Not calling passport.initialize() and passport.session() middleware in the right order.
  • Using wrong callback URLs that don't match OAuth provider settings.
  • Not handling user serialization and deserialization properly, which breaks session support.
javascript
/* Wrong: Missing session middleware */
app.use(passport.initialize());
app.use(passport.session());

/* Right: Include session before passport middleware */
app.use(session({ secret: 'secret', resave: false, saveUninitialized: true }));
app.use(passport.initialize());
app.use(passport.session());
📊

Quick Reference

  • Install passport and provider strategy (e.g., passport-google-oauth20).
  • Configure strategy with client ID, secret, and callback URL.
  • Use express-session to enable sessions.
  • Set up routes for login and callback.
  • Protect routes by checking req.isAuthenticated().

Key Takeaways

Use Passport.js with an OAuth strategy to handle OAuth in Express easily.
Always configure express-session before passport middleware for session support.
Set correct callback URLs in both your app and OAuth provider settings.
Protect routes by checking if the user is authenticated with req.isAuthenticated().
Serialize and deserialize user data to maintain login state across requests.