express-subdomain

raw JSON →
1.0.6 verified Sat Apr 25 auth: no javascript maintenance

Simple and lightweight middleware for handling subdomains in Express.js applications. Current stable version is 1.0.6, with minimal releases since initial publication. Key differentiators: zero dependencies, supports multi-level subdomains, wildcards, and chaining. Simpler than alternatives like vhost, focusing only on subdomain routing without virtual hosting features.

error Cannot find module 'express-subdomain'
cause Package not installed or used in a non-ESM context without proper import.
fix
Run 'npm install express-subdomain' and use 'import subdomain from 'express-subdomain'' in ESM code.
error TypeError: subdomain is not a function
cause Attempted to use named import instead of default import.
fix
Use 'import subdomain from 'express-subdomain'' (default import) instead of 'import { subdomain }...'.
gotcha Subdomain middleware must be registered before other routes that match the base domain, otherwise Express may match base routes first.
fix Ensure app.use(subdomain(...)) is placed before app.get('/', ...).
gotcha Wildcard subdomains (e.g., '*.api') match any single subdomain part, not multi-level wildcards.
fix Use explicit multi-level subdomain strings like 'v1.api' or chain subdomain middleware for deeper nesting.
gotcha Subdomain resolution depends on the Host header; local development requires proper hosts file entries (e.g., 'subdomain.localhost' may not work).
fix Add entries to /etc/hosts or use tools like ngrok to test subdomains.
npm install express-subdomain
yarn add express-subdomain
pnpm add express-subdomain

Demonstrates basic subdomain routing with Express Router and wildcard subdomain middleware.

import express from 'express';
import subdomain from 'express-subdomain';

const app = express();
const apiRouter = express.Router();

apiRouter.get('/', (req, res) => {
  res.send('Welcome to API');
});

app.use(subdomain('api', apiRouter));

app.get('/', (req, res) => {
  res.send('Homepage');
});

app.listen(3000, () => console.log('Server running on port 3000'));