express-api-key
v1.0.9
Published
Express middleware for API key authentication, role-based access, and rate limiting.
Maintainers
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-keyPeer dependencies: You must also install
express,mongoose, andrate-limiter-flexiblein 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 5000Generate API Keys
npx api_key_express genkeys <role> <daysValid> <count>
# Example:
npx api_key_express genkeys premium 30 10Note: Requires
MONGODB_URIin your environment.
API Key Generation (Discord Bot)
- Set up your Discord bot token and authorized user IDs as environment variables:
DISCORD_TOKEN=your-bot-tokenAUTHORIZED_USER_IDS=comma,separated,discord,ids
- Run the bot:
node dist/discord/bot.js - Use the command in Discord:
!genkeys <count> <role> <daysValid> <endpoints> # Example: !genkeys 5 premium 30 /api/data,/api/other - The bot will DM you a
.txtfile 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:
- Generate keys using the CLI or Discord bot and save the
.txtfile. - Upload the keys as "license keys" or "digital products" to your chosen platform.
- Configure automatic delivery so buyers receive a key upon purchase.
- 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-keyPeer dependencies: You must also install
express,mongoose, andrate-limiter-flexiblein 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)
- Set up your Discord bot token and authorized user IDs as environment variables:
DISCORD_TOKEN=your-bot-tokenAUTHORIZED_USER_IDS=comma,separated,discord,ids
- Run the bot:
node dist/discord/bot.js - Use the command in Discord:
!genkeys <count> <role> <daysValid> <endpoints> # Example: !genkeys 5 premium 30 /api/data,/api/other - The bot will DM you a
.txtfile 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
