Providing multi-tenant schema-switching example
I'm preparing a Node.js Express example showing middleware that detects tenant from the subdomain and sets the Postgres search_path per request using a shared connection pool, illustrating schema-per-tenant with proper client acquisition and release.
Below is a simple example of how you can build a multi-tenant REST API with Express and Node.js, using a single Postgres database and one connection pool, while switching schemas based on the subdomain in each request.
Key ideas
- Tenant detection from subdomain: Parse the incoming request’s host and treat the first segment as the tenant identifier (e.g.,
tenant1.example.com ⇒ tenant ID = tenant1).
- Shared Postgres pool: Use
pg’s Pool with a single connection string.
- Schema switching per request: For each request, set the
search_path to the tenant’s schema. This allows you to isolate data in separate schemas. (If you actually want database-per-tenant, you’d create pools dynamically per database name instead of setting search_path.)
Example structure
project/
├─ app.js
├─ .env
└─ package.json
app.js
require('dotenv').config();
const express = require('express');
const { Pool } = require('pg');
const app = express();
app.use(express.json());
// Shared pool for all tenants (same DB, different schemas)
const pool = new Pool({
connectionString: process.env.DATABASE_URL,
// tune for your needs
max: 20, // maximum number of clients
idleTimeoutMillis: 30000, // close idle clients after 30 seconds
connectionTimeoutMillis: 2000, // return an error after 2s if connection could not be established
});
// Sanitize your tenant ID to avoid SQL injection or invalid schema names.
// A simple example is to allow alphanumeric + underscore only.
function sanitizeTenantId(tenantId) {
return tenantId.replace(/[^a-zA-Z0-9_]/g, '');
}
// Extract tenant from subdomain
function tenantMiddleware(req, res, next) {
const host = req.headers.host || '';
// e.g. tenant1.example.com -> tenant1
const subdomain = host.split('.')[0];
// fallback if no subdomain recognized
const tenantId = subdomain && subdomain !== 'www' ? subdomain : 'default';
req.tenantId = sanitizeTenantId(tenantId);
next();
}
// Attach a DB client and set search_path for each request
async function dbClientMiddleware(req, res, next) {
const client = await pool.connect();
try {
// Set search_path to the tenant schema (and public as fallback)
const schema = req.tenantId;
await client.query(`SET search_path TO ${schema}, public`);
req.db = client;
next();
} catch (err) {
client.release();
next(err);
}
}
// Release the DB client after the response
function releaseDbClientMiddleware(req, res, next) {
if (req.db) {
req.db.release();
}
next();
}
// Wire up middlewares
app.use(tenantMiddleware);
app.use(dbClientMiddleware);
// Example routes
app.get('/users', async (req, res, next) => {
try {
const result = await req.db.query('SELECT * FROM users');
res.json(result.rows);
} catch (err) {
next(err);
}
});
app.post('/users', async (req, res, next) => {
const { name, email } = req.body;
try {
const result = await req.db.query(
'INSERT INTO users(name, email) VALUES($1, $2) RETURNING *',
[name, email]
);
res.status(201).json(result.rows[0]);
} catch (err) {
next(err);
}
});
// Error handler
app.use((err, req, res, next) => {
console.error('Error', err);
res.status(500).json({ error: 'Server error' });
});
// Release DB client after response is done
app.use(releaseDbClientMiddleware);
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`Multi-tenant API listening on port ${port}`);
});
.env example
DATABASE_URL=postgres://username:password@localhost:5432/my_multitenant_db
PORT=3000
Notes
- Schema-per-tenant: This example uses
SET search_path to switch schemas based on the subdomain. Make sure each tenant’s schema exists and has the correct tables.
- Database-per-tenant: If you truly want a separate DB per tenant, you’d maintain a mapping of tenant → connection string and create or reuse a dedicated
Pool per database. In that scenario, you wouldn’t set search_path; you’d connect to the right DB instead.
- Validation and security: Always sanitize the tenant name and enforce strong validation to avoid SQL injection or invalid schema names.
- Connection pooling: Tune
max, idleTimeoutMillis, and other pool options based on your expected traffic.
- Migrations: Consider a migration strategy to create/upgrade schemas for new tenants.
- Production readiness: Add rate limiting, logging, request validation, and proper error handling for a production SaaS.