Passport.js is primarily designed to work with Express.js, as it relies on Express's middleware architecture to handle authentication and manage user sessions. However, if you want to use Passport.js without Express or use middleware without Express, you can do so by creating your own custom middleware stack.

Here's a high-level outline of how you can achieve this:

  1. Create Your Middleware Stack: Instead of using Express.js, you'll need to build your own custom middleware stack using a plain Node.js HTTP server or another framework of your choice. You can use the Node.js built-in http module or frameworks like Koa, Fastify, or Hapi.

  2. Initialize Passport: You can still use Passport.js for authentication, even without Express. Initialize Passport and set up the authentication strategies you want to use (e.g., LocalStrategy, JWTStrategy, etc.).

  3. Create Custom Middleware: Passport.js exposes a passport.initialize() middleware that is responsible for initializing Passport and making it available on the request object. You'll need to create your own custom middleware that emulates this functionality.

    const passport = require('passport'); // Your custom middleware function function initializePassport(req, res, next) { // Create a session object or attach Passport to an existing session management system // For example, if you're using the built-in `http` module, you can create a session like this: req.session = {}; // Initialize Passport and attach it to the request object passport.initialize()(req, res, next); }
  4. Implement Your Routes: Handle your application's routes and apply your custom middleware when needed. For protected routes that require authentication, use Passport's authentication middleware (e.g., passport.authenticate()).

    // Example route with custom middleware and Passport's authentication middleware app.get('/protected', initializePassport, passport.authenticate('local', { session: false }), (req, res) => { // Handle the protected route logic here });
  5. Start the Server: Start your HTTP server and listen for incoming requests.

Remember that using Passport.js without Express means that you'll need to handle various aspects of the middleware stack and request handling that Express typically manages for you. This approach gives you more control and flexibility, but it also requires you to handle additional details.

While using Passport.js without Express is possible, keep in mind that Passport.js was specifically designed to work with Express.js, and using it with other frameworks might require more effort and custom code. If you're using a different framework, check if it has built-in authentication and middleware support or consider using a dedicated authentication library that is more suitable for your specific framework.

Have questions or queries?
Get in Touch