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 🙏

© 2026 – Pkg Stats / Ryan Hefner

express-api-key

v1.0.9

Published

Express middleware for API key authentication, role-based access, and rate limiting.

Readme

express-api-key

A robust, reusable Express middleware for API key authentication, role-based access control, and rate limiting. Includes a Discord bot for key generation and a flexible MongoDB schema for scalable API protection.


Installation

npm install express-api-key

Peer dependencies: You must also install express, mongoose, and rate-limiter-flexible in your project.


Quick Start

1. Configure MongoDB Models

Ensure your MongoDB instance is running and your models are set up as in src/models/ApiKey.ts and src/models/Role.ts.

2. Integrate Middleware

import express from 'express';
import mongoose from 'mongoose';
import { createApiKeyMiddlewareWithConnection } from 'express-api-key';

const app = express();
app.use(express.json());

mongoose.connect('mongodb://localhost:27017/your-db');

app.use(createApiKeyMiddlewareWithConnection(mongoose, { headerName: 'x-api-key' }));

app.get('/protected', (req, res) => {
  res.json({ message: 'You are authenticated!', apiKey: (req as any).apiKeyDoc });
});

CLI Usage

This package provides a CLI for managing roles and generating API keys.

Create or Update a Role

npx api_key_express role <name> <minIntervalSeconds> <maxMonthlyUsage>
# Example:
npx api_key_express role premium 1 5000

Generate API Keys

npx api_key_express genkeys <role> <daysValid> <count>
# Example:
npx api_key_express genkeys premium 30 10

Note: Requires MONGODB_URI in your environment.


API Key Generation (Discord Bot)

  1. Set up your Discord bot token and authorized user IDs as environment variables:
    • DISCORD_TOKEN=your-bot-token
    • AUTHORIZED_USER_IDS=comma,separated,discord,ids
  2. Run the bot:
    node dist/discord/bot.js
  3. Use the command in Discord:
    !genkeys <count> <role> <daysValid> <endpoints>
    # Example: !genkeys 5 premium 30 /api/data,/api/other
  4. The bot will DM you a .txt file with the generated keys.

Roles & Restrictions

  • Define roles in MongoDB (RoleModel). Example:
    {
      name: 'premium',
      minIntervalSeconds: 1,
      maxMonthlyUsage: 5000
    }
  • Assign roles to API keys. Restrictions (rate limits, endpoints, etc.) are enforced dynamically per role.

Error Responses

  • 401 { error: 'API key missing' }
  • 401 { error: 'Invalid API key' }
  • 401 { error: 'API key expired' }
  • 429 { error: 'Requests must be at least X seconds apart' }
  • 429 { error: 'Monthly quota exceeded' }
  • 401 { error: 'Endpoint not allowed for your role' }
  • 401 { error: 'Insufficient permissions' }

How to Sell API Keys

You can sell API keys generated by this package using platforms like Sellpass, Gumroad, or LemonSqueezy:

  1. Generate keys using the CLI or Discord bot and save the .txt file.
  2. Upload the keys as "license keys" or "digital products" to your chosen platform.
  3. Configure automatic delivery so buyers receive a key upon purchase.
  4. Rotate and replenish your key stock as needed.

Tip: Never expose your MongoDB or backend credentials to buyers. Only deliver the API key string.


Best Practices

  • Store keys securely: Never expose API keys in client-side code.
  • Rotate keys: Expire and regenerate keys regularly.
  • Use roles: Assign roles to group users and manage restrictions centrally.
  • Monitor usage: Track and alert on suspicious or excessive usage.
  • Keep dependencies updated: Regularly update this package and its peer dependencies.

Example Usage

// See example.ts for a full working demo
import { createApiKeyMiddlewareWithConnection, allowRoles } from 'express-api-key';
app.use(createApiKeyMiddlewareWithConnection(mongoose));
app.get('/data', (req, res) => res.json({ ok: true }));
app.get('/admin', allowRoles(['mega']), (req, res) => res.json({ admin: true }));

License

MIT


express-api-key

A robust, reusable Express middleware for API key authentication, role-based access control, and rate limiting. Includes a Discord bot for key generation and a flexible MongoDB schema for scalable API protection.


Installation

npm install express-api-key

Peer dependencies: You must also install express, mongoose, and rate-limiter-flexible in your project.


Quick Start

1. Configure MongoDB Models

Ensure your MongoDB instance is running and your models are set up as in src/models/ApiKey.ts and src/models/Role.ts.

2. Integrate Middleware

import express from 'express';
import mongoose from 'mongoose';
import { createApiKeyMiddleware } from 'express-api-key';

const app = express();
app.use(express.json());

mongoose.connect('mongodb://localhost:27017/your-db');

app.use(createApiKeyMiddleware({ headerName: 'x-api-key' }));

app.get('/protected', (req, res) => {
  res.json({ message: 'You are authenticated!', apiKey: (req as any).apiKeyDoc });
});

API Key Generation (Discord Bot)

  1. Set up your Discord bot token and authorized user IDs as environment variables:
    • DISCORD_TOKEN=your-bot-token
    • AUTHORIZED_USER_IDS=comma,separated,discord,ids
  2. Run the bot:
    node dist/discord/bot.js
  3. Use the command in Discord:
    !genkeys <count> <role> <daysValid> <endpoints>
    # Example: !genkeys 5 premium 30 /api/data,/api/other
  4. The bot will DM you a .txt file with the generated keys.

Roles & Restrictions

  • Define roles in MongoDB (RoleModel). Example:
    {
      name: 'premium',
      allowedEndpoints: ['/data', '/premium'],
      minIntervalSeconds: 1,
      maxMonthlyUsage: 5000,
      permissions: [{ endpoint: '/premium', method: 'GET' }]
    }
  • Assign roles to API keys. Restrictions (rate limits, endpoints, etc.) are enforced dynamically per role.

Error Responses

  • 401 { error: 'API key missing' }
  • 401 { error: 'Invalid API key' }
  • 401 { error: 'API key expired' }
  • 429 { error: 'Requests must be at least X seconds apart' }
  • 429 { error: 'Monthly quota exceeded' }
  • 401 { error: 'Endpoint not allowed for your role' }
  • 401 { error: 'Insufficient permissions' }

Best Practices

  • Store keys securely: Never expose API keys in client-side code.
  • Rotate keys: Expire and regenerate keys regularly.
  • Use roles: Assign roles to group users and manage restrictions centrally.
  • Monitor usage: Track and alert on suspicious or excessive usage.
  • Keep dependencies updated: Regularly update this package and its peer dependencies.

Example Usage

// See example.ts for a full working demo
app.use(createApiKeyMiddleware());
app.get('/data', (req, res) => res.json({ ok: true }));

License

MIT