Passport.js Deployment and Usage Guide
Prerequisites
- Node.js (version 12.0.0 or higher)
- npm (version 6.0.0 or higher)
- Express.js (for web application framework)
- Session middleware (such as
express-sessionorcookie-session) - Database (for user storage, depending on your strategy)
Installation
-
Install Passport.js
npm install passport -
Install a strategy (choose one or more based on your authentication needs)
# Example: Local strategy for username/password npm install passport-local # Example: Google OAuth strategy npm install passport-google-oauth20 # Example: Facebook OAuth strategy npm install passport-facebook -
Install session middleware
npm install express-session
Configuration
Basic Setup
-
Initialize Passport in your Express app
const express = require('express'); const session = require('express-session'); const passport = require('passport'); const app = express(); // Session middleware (must be used before passport.initialize()) app.use(session({ secret: 'your_secret_key', resave: false, saveUninitialized: false })); // Initialize Passport app.use(passport.initialize()); app.use(passport.session()); -
Configure a strategy
const LocalStrategy = require('passport-local').Strategy; passport.use(new LocalStrategy( function(username, password, done) { User.findOne({ username: username }, function (err, user) { if (err) { return done(err); } if (!user) { return done(null, false); } if (!user.verifyPassword(password)) { return done(null, false); } return done(null, user); }); } )); -
Serialize and deserialize user
passport.serializeUser(function(user, done) { done(null, user.id); }); passport.deserializeUser(function(id, done) { User.findById(id, function(err, user) { done(err, user); }); });
Environment Variables
Create a .env file with your configuration:
SESSION_SECRET=your_secret_key_here
GOOGLE_CLIENT_ID=your_google_client_id
GOOGLE_CLIENT_SECRET=your_google_client_secret
FACEBOOK_APP_ID=your_facebook_app_id
FACEBOOK_APP_SECRET=your_facebook_app_secret
Build & Run
Development
-
Start your application
node app.js -
Or use nodemon for automatic restarts
npm install -g nodemon nodemon app.js
Production
-
Use a process manager
npm install -g pm2 pm2 start app.js --name "my-app" -
Set NODE_ENV to production
NODE_ENV=production node app.js
Deployment
Platform Options
-
Heroku
# Create Heroku app heroku create your-app-name # Deploy git push heroku main # Set environment variables heroku config:set SESSION_SECRET=your_secret_key -
Vercel
- Create a
vercel.jsonfile - Deploy using
vercelCLI - Set environment variables in Vercel dashboard
- Create a
-
AWS Elastic Beanstalk
- Create application
- Upload application bundle
- Configure environment variables in EB console
-
DigitalOcean App Platform
- Connect repository
- Configure environment variables
- Deploy automatically on push
Troubleshooting
Common Issues
-
"Login sessions require session support"
- Ensure
express-sessionmiddleware is configured beforepassport.initialize() - Check that session middleware is properly mounted
- Ensure
-
Authentication fails silently
- Verify strategy configuration
- Check database connection
- Ensure user verification logic is correct
-
Session data not persisting
- Check session store configuration
- Verify session cookie settings
- Ensure session middleware is before passport middleware
-
Strategy not found
- Ensure strategy is properly installed via npm
- Verify strategy is registered with
passport.use()
Debug Mode
Enable debug logging for Passport:
DEBUG=passport* node app.js
Session Storage
For production, consider using a session store:
npm install connect-redis
const session = require('express-session');
const RedisStore = require('connect-redis')(session);
const redis = require('redis');
app.use(session({
store: new RedisStore({ client: redis.createClient() }),
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: false
}));
Security Best Practices
- Use HTTPS in production
- Set secure cookies
- Implement rate limiting
- Use environment variables for secrets
- Regularly update dependencies
- Validate and sanitize user input