npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

express-auth-magic-routes

v1.0.7

Published

Express authentication routes with Firebase and Magic Link support

Readme

Express Auth Magic Routes

A comprehensive authentication routes package for Express.js applications with support for Firebase authentication, Magic Link authentication, and MongoDB integration.

Features

  • 🔥 Firebase Authentication
  • ✨ Magic Link Authentication
  • 🚀 Rate Limiting
  • 🔒 Token Validation & Blacklisting
  • 📧 Email Domain Validation
  • 🎫 JWT Token Management
  • 📊 MongoDB Integration
  • 🎁 Referral System Support
  • 📝 Swagger Documentation

Installation

npm install express-auth-magic-routes

Environment Variables

# MongoDB Configuration (Option 1: Using URI)
MONGO_URI=mongodb+srv://username:[email protected]/database

# MongoDB Configuration (Option 2: Using separate parameters)
MONGO_USERNAME=your_username
MONGO_PASSWORD=your_password
MONGO_HOST=cluster.mongodb.net
MONGO_DATABASE=your_database
MONGO_PORT=27017  # Optional, defaults to 27017

# Firebase Configuration
FIREBASE_TYPE=service_account
FIREBASE_PROJECT_ID=your-project-id
FIREBASE_PRIVATE_KEY_ID=your-private-key-id
FIREBASE_PRIVATE_KEY="your-private-key"  # Include quotes to handle newlines
FIREBASE_CLIENT_EMAIL=your-client-email
FIREBASE_CLIENT_ID=your-client-id
FIREBASE_AUTH_URI=https://accounts.google.com/o/oauth2/auth
FIREBASE_TOKEN_URI=https://oauth2.googleapis.com/token
FIREBASE_AUTH_CERT_URL=https://www.googleapis.com/oauth2/v1/certs
FIREBASE_CLIENT_CERT_URL=your-client-cert-url

# JWT Configuration
JWT_SECRET=your-jwt-secret

# Environment
NODE_ENV=development  # or production

Usage

const express = require('express');
const { authRouter, initializeAuth } = require('express-auth-magic-routes');

const app = express();

// Initialize auth with your configuration
await initializeAuth({
    jwtSecret: process.env.JWT_SECRET,
    mongodb: {
        options: {
            useNewUrlParser: true,
            useUnifiedTopology: true,
            maxPoolSize: 10
        }
    },
    firebaseConfig: {
        type: process.env.FIREBASE_TYPE,
        project_id: process.env.FIREBASE_PROJECT_ID,
        private_key_id: process.env.FIREBASE_PRIVATE_KEY_ID,
        private_key: process.env.FIREBASE_PRIVATE_KEY?.replace(/\\n/g, '\n'),
        client_email: process.env.FIREBASE_CLIENT_EMAIL,
        client_id: process.env.FIREBASE_CLIENT_ID,
        auth_uri: process.env.FIREBASE_AUTH_URI,
        token_uri: process.env.FIREBASE_TOKEN_URI,
        auth_provider_x509_cert_url: process.env.FIREBASE_AUTH_CERT_URL,
        client_x509_cert_url: process.env.FIREBASE_CLIENT_CERT_URL
    },
    mailService: {
        sendMagicLinkEmail: async (email, token) => {
            // Implement your email sending logic
        }
    }
});

// Use the auth routes
app.use('/auth', authRouter);

API Routes

Firebase Authentication

POST /auth
Content-Type: application/json

Request:

{
    "idToken": "firebase-id-token",
    "referralCode": "optional-referral-code"
}

Response:

{
    "status": "success",
    "data": {
        "token": "jwt-token",
        "user": {
            "uid": "user-id",
            "email": "[email protected]",
            "name": "User Name",
            "picture": "profile-picture-url",
            "referralCode": "USER123"
        }
    }
}

Magic Link Authentication

Request Magic Link:

POST /auth/magic-link
Content-Type: application/json

Request:

{
    "email": "[email protected]",
    "referralCode": "optional-referral-code"
}

Response:

{
    "status": "success",
    "data": {
        "message": "Magic link sent successfully"
    }
}

Verify Magic Link:

POST /auth/verify-magic-link
Content-Type: application/json

Request:

{
    "token": "magic-link-token"
}

Response:

{
    "status": "success",
    "data": {
        "token": "jwt-token",
        "user": {
            "uid": "user-id",
            "email": "[email protected]",
            "name": "User Name",
            "referralCode": "USER123"
        }
    }
}

Token Validation

GET /auth/validate
Authorization: Bearer jwt-token

Response:

{
    "status": "success",
    "data": {
        "valid": true,
        "user": {
            "uid": "user-id",
            "email": "[email protected]",
            "name": "User Name"
        }
    }
}

Logout

POST /auth/logout
Authorization: Bearer jwt-token

Response:

{
    "status": "success",
    "message": "Successfully logged out"
}

Swagger Documentation

Add this to your Swagger configuration:

/**
 * @swagger
 * components:
 *   securitySchemes:
 *     BearerAuth:
 *       type: http
 *       scheme: bearer
 *       bearerFormat: JWT
 *   schemas:
 *     User:
 *       type: object
 *       properties:
 *         uid:
 *           type: string
 *           example: "user123"
 *         email:
 *           type: string
 *           format: email
 *           example: "[email protected]"
 *         name:
 *           type: string
 *           example: "John Doe"
 *         picture:
 *           type: string
 *           example: "https://example.com/profile.jpg"
 *         referralCode:
 *           type: string
 *           example: "USER123"
 *     Error:
 *       type: object
 *       properties:
 *         status:
 *           type: string
 *           example: "error"
 *         message:
 *           type: string
 *         code:
 *           type: string
 */

/**
 * @swagger
 * tags:
 *   name: Auth
 *   description: Authentication endpoints
 */

/**
 * @swagger
 * /auth:
 *   post:
 *     summary: Authenticate with Firebase
 *     tags: [Auth]
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             required:
 *               - idToken
 *             properties:
 *               idToken:
 *                 type: string
 *               referralCode:
 *                 type: string
 *     responses:
 *       200:
 *         description: Authentication successful
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 status:
 *                   type: string
 *                   example: success
 *                 data:
 *                   type: object
 *                   properties:
 *                     token:
 *                       type: string
 *                     user:
 *                       $ref: '#/components/schemas/User'
 */

// ... More Swagger documentation for other routes

Configuration Options

initializeAuth({
    jwtSecret: 'your-jwt-secret',
    jwtExpiresIn: '30d',
    magicLinkExpiryMinutes: 15,
    rateLimiting: {
        windowMs: 15 * 60 * 1000, // 15 minutes
        max: 150 // limit each IP to 150 requests per windowMs
    },
    allowedEmailDomains: ['gmail.com', 'yahoo.com'],
    mongodb: {
        options: {
            useNewUrlParser: true,
            useUnifiedTopology: true,
            maxPoolSize: 10,
            serverSelectionTimeoutMS: 5000,
            socketTimeoutMS: 45000
        }
    }
});

Error Handling

The package includes comprehensive error handling with these error codes:

  • AUTH_REQUIRED: Authentication token is missing
  • INVALID_TOKEN: Invalid or expired token
  • INVALID_TOKEN_FORMAT: Malformed token
  • TOKEN_REVOKED: Token has been blacklisted
  • AUTH_FAILED: Firebase authentication failed
  • INVALID_EMAIL: Invalid email format
  • UNSUPPORTED_EMAIL_DOMAIN: Email domain not allowed
  • RATE_LIMIT_EXCEEDED: Too many requests
  • INVALID_MAGIC_LINK: Invalid or expired magic link
  • MONGO_CONNECTION_ERROR: MongoDB connection failed

Security Features

  • Rate limiting for magic link requests
  • Token blacklisting for logout
  • Email domain validation
  • Secure cookie handling
  • JWT token validation
  • MongoDB connection pooling
  • Request validation
  • Error handling
  • Logging

MongoDB Schemas

The package includes these MongoDB models:

  • User
  • MagicLink
  • BlacklistedToken

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

ISC