The user wants to design a scalable REST API using Node.js and Express that includes multi-tenant authentication and rate limiting. This involves outlining the architecture, including stateless design, JWT for authentication, and required middleware. I need to consider a database schema that includes a tenants table and address routing and error handling effectively. For multi-tenancy, I’ll evaluate options like database-per-tenant or schema-per-tenant. I'll also include a plan for rate limiting and relevant libraries. A concise overview that mixes structure with some sample code should work well!Structuring the API design
I’m thinking that I need more structure in the API design by including headings such as Requirements & Assumptions, High-level Architecture, Multi-tenant Authentication, Rate Limiting, Example Code Skeleton, and Security & Scalability Considerations. I don’t need to dive deeply into every detail but should include some code for middleware that handles authentication and rate limiting using JWT, tenantId, and roles. I’ll illustrate how to retrieve tenant configurations. Let's create a clear layout to guide the design effectively!Detailing the architecture flow
I’m mapping out the authentication flow that includes a POST request to /auth/login, which verifies the user within a tenant and issues a JWT with the subject, tenantId, and roles. The middleware should verify the JWT by decoding it and checking that the tenantId from the token matches the route parameter or header to deny cross-tenant access.
Next, for rate limiting, I’ll use express-rate-limit with Redis to manage the limits for each tenant and user, plus factor in a folder structure for organization. Additionally, I'll ensure scalability with stateless design and cloud load balancers!Choosing the right setup
It looks like the user hasn't specified the audience, but I’m guessing it's at a developer level. I’ll decide to code in JavaScript and opt for the modern syntax with ES modules since Node 18+ supports it. But I’m aware both CommonJS and ES modules are acceptable. To reduce confusion, I’ll include comments in the code.
First, I’ll prepare by installing the necessary packages using npm. For the multi-tenant setup, I plan to use a path-based approach like /api/:tenantId/... to keep it clear, with the tenantValidation middleware ensuring users belong to that tenant.Crafting a scalable REST API
I’m outlining the implementation of a rate limiter using express-rate-limit alongside Redis for multi-tenant authentication. First, I'll set up the rate limiter with a configuration for each tenant’s request limits. The JWT payload will include the user's ID, tenant ID, and role for proper authentication. I'll incorporate error handling and suggest using HTTPS in production.
Next, I'll develop a structured architecture with high-level design points, a description of core multi-tenancy concepts, and example implementations for key files like app.js and middleware. I’ll emphasize scalability best practices without overloading the explanation! Below is a design and example implementation outline for a scalable, multi-tenant REST API in Node.js + Express with authentication and rate limiting.
1. High-level design
Core characteristics:
Node.js + Express, stateless REST API
Tenants are first-class (each request is scoped to a tenant)
Multi-tenant authentication via JWT (each token includes tenantId)
Per-tenant and/or per-user rate limiting using Redis (so it scales horizontally)
Clean separation via middlewares: tenant resolution → auth → rate limiting → business logic
Ready for horizontal scaling behind a load balancer
For clarity, this example uses path-based tenancy: /api/:tenantId/....
Data model (simplified):
text
tenants
id (string, PK)
name
rate_limit_per_minute
status (active, suspended, ...)
users
id (string, PK)
tenant_id (FK → tenants.id)
email
password_hash
role (admin, user, ...)
projects (example resource)
id
tenant_id
name
...
All tenant data is either:
In a single shared DB with a tenant_id column on each table (simplest), or
Mapped to separate schemas/databases per tenant (more isolation; more complex).
The code below assumes the shared DB approach.
3. Authentication flow (per tenant)
Client calls: POST /api/:tenantId/auth/login with email + password.
Server:
Validates tenant exists and is active
Looks up user by email + tenantId
Verifies password (e.g. bcrypt)
Issues JWT with payload: { sub: user.id, tenantId, role }
Client includes Authorization: Bearer <token> on all subsequent calls.
Auth middleware:
Verifies token signature
Ensures token tenantId matches the URL :tenantId
Attaches req.user and req.tenant
4. Rate limiting strategy
Shared state via Redis so that rate limiting works across multiple instances.
Keyed by tenant + user or tenant + IP.
Per-tenant configuration: tenant.rate_limit_per_minute from DB.
Example policy: each tenant has a total budget per minute, optionally subdivided per user.
// Using ioredis as an example
import Redis from 'ioredis';
export const redisClient = new Redis(process.env.REDIS_URL);
// Configure TLS, auth, retry strategy as needed
src/app.js
js
import express from 'express';
import helmet from 'helmet';
import cors from 'cors';
import authRouter from './routes/auth.js';
import projectsRouter from './routes/projects.js';
import { tenantContext } from './middleware/tenantContext.js';
import { authRequired } from './middleware/auth.js';
import { tenantRateLimiter } from './middleware/rateLimiter.js';
const app = express();
app.use(helmet());
app.use(cors());
app.use(express.json());
// Versioned API: /api/v1/:tenantId/...
app.use('/api/v1/:tenantId', tenantContext, authRouter); // login/register
app.use(
'/api/v1/:tenantId/projects',
tenantContext,
authRequired,
tenantRateLimiter,
projectsRouter
);
// Generic error handler
app.use((err, req, res, next) => {
console.error(err);
const status = err.status || 500;
res.status(status).json({ error: err.message || 'Internal server error' });
});
export default app;
server.js
js
import http from 'http';
import app from './src/app.js';
const PORT = process.env.PORT || 3000;
const server = http.createServer(app);
server.listen(PORT, () => {
console.log(`API listening on port ${PORT}`);
});
7. Tenant context middleware
src/services/tenantService.js (stub)
js
// In reality you'd use an ORM or DB client, here it's just a stub
export async function getTenantById(tenantId) {
// e.g., SELECT * FROM tenants WHERE id = $1 AND status = 'active'
return {
id: tenantId,
name: 'Example Tenant',
rate_limit_per_minute: 6000, // configurable per tenant
status: 'active',
};
}
src/middleware/tenantContext.js
js
import { getTenantById } from '../services/tenantService.js';
export async function tenantContext(req, res, next) {
try {
const { tenantId } = req.params;
if (!tenantId) {
return res.status(400).json({ error: 'Missing tenantId in path' });
}
const tenant = await getTenantById(tenantId);
if (!tenant || tenant.status !== 'active') {
return res.status(404).json({ error: 'Tenant not found or inactive' });
}
req.tenant = tenant; // attach tenant to request
next();
} catch (err) {
next(err);
}
}
8. Authentication: login + JWT verification
src/services/userService.js (stub)
js
import bcrypt from 'bcrypt';
export async function findUserByEmailAndTenant(tenantId, email) {
// SELECT * FROM users WHERE tenant_id = $1 AND email = $2
// Stub:
if (email === 'user@example.com') {
return {
id: 'user-123',
tenant_id: tenantId,
email,
password_hash: await bcrypt.hash('password123', 10),
role: 'admin',
};
}
return null;
}
export async function verifyPassword(password, passwordHash) {
return bcrypt.compare(password, passwordHash);
}