Providing minimal multi-tenant Next.js + Prisma + Tailwind boilerplate
Below is a concise boilerplate setup demonstrating subdomain-based routing middleware, Prisma clients with separate connection pools per tenant, and minimal Tailwind CSS configuration. It rewrites requests based on the subdomain, dynamically selects the tenant’s database, and applies Tailwind styles globally.
middleware.ts – rewrites requests from tenant.example.com to /tenant path:
import { NextRequest, NextResponse } from 'next/server'
export function middleware(req: NextRequest) {
const hostname = req.headers.get('host') ?? ''
const currentHost = hostname.split(':')[0]
const subdomain = currentHost.split('.').length > 2 ? currentHost.split('.')[0] : null
if (subdomain && subdomain !== 'www' && currentHost !== 'localhost') {
const url = req.nextUrl.clone()
url.pathname = `/${subdomain}${url.pathname}`
return NextResponse.rewrite(url)
}
return NextResponse.next()
}
lib/prisma.ts – manages Prisma clients per tenant using environment variables for DB URLs:
import { PrismaClient } from '@prisma/client'
const globalAny = global as any
const clients: Record<string, PrismaClient> = globalAny.tenantPrismaClients || {}
export function getPrisma(tenant: string) {
if (clients[tenant]) return clients[tenant]
const dbUrl =
process.env[`DATABASE_URL_${tenant.toUpperCase()}`] || process.env.DATABASE_URL
clients[tenant] = new PrismaClient({
datasources: { db: { url: dbUrl } },
})
if (process.env.NODE_ENV !== 'production') globalAny.tenantPrismaClients = clients
return clients[tenant]
}
prisma/schema.prisma – minimal schema for all tenants:
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
generator client {
provider = "prisma-client-js"
}
model User {
id Int @id @default(autoincrement())
email String @unique
name String?
createdAt DateTime @default(now())
}
pages/[tenant]/index.tsx – fetches tenant-specific data server-side:
import { getPrisma } from '../../lib/prisma'
export async function getServerSideProps({ params }) {
const tenant = params.tenant as string
const prisma = getPrisma(tenant)
const users = await prisma.user.findMany()
return { props: { tenant, users } }
}
export default function TenantPage({ tenant, users }) {
return (
<div>
<h1>Tenant: {tenant}</h1>
<ul>
{users.map(user => (
<li key={user.id}>{user.email}</li>
))}
</ul>
</div>
)
}
pages/_app.tsx – imports global Tailwind styles:
import '../styles/globals.css'
import type { AppProps } from 'next/app'
export default function MyApp({ Component, pageProps }: AppProps) {
return <Component {...pageProps} />
}
pages/index.tsx – default landing page for hosts without subdomain:
export default function Home() {
return <h1>Welcome to the Multi-Tenant App</h1>
}
tailwind.config.js – minimal Tailwind config specifying content files:
module.exports = {
content: ['./pages/**/*.{js,ts,jsx,tsx}', './components/**/*.{js,ts,jsx,tsx}'],
theme: { extend: {} },
plugins: [],
}
postcss.config.js – config for Tailwind and autoprefixer:
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
}
styles/globals.css – imports Tailwind base and utilities:
@tailwind base;
@tailwind components;
@tailwind utilities;
Environment variables (.env example):
DATABASE_URL=postgresql://root:pass@localhost:5432/default_db
DATABASE_URL_TENANT1=postgresql://root:pass@localhost:5432/tenant1
DATABASE_URL_TENANT2=postgresql://root:pass@localhost:5432/tenant2
This setup dynamically rewrites requests based on subdomains, maps tenants to separate Prisma clients with individual connection pools, and applies Tailwind CSS globally. For production with many tenants, consider optimized connection pooling solutions like PgBouncer to manage database load efficiently.
Below is a minimal Next.js + Prisma + Tailwind CSS setup with multi-tenancy. It uses middleware to rewrite requests based on the subdomain and configures Prisma to create or reuse tenant-specific clients (and therefore connection pools) per request. Adapt paths or naming to your preferred structure.
1) Install dependencies
npm install next react react-dom prisma @prisma/client tailwindcss postcss autoprefixer
npx tailwindcss init -p
npx prisma init
2) Tailwind setup
tailwind.config.js
/** @type {import('tailwindcss').Config} */
module.exports = {
content: [
"./pages/**/*.{js,ts,jsx,tsx}",
"./components/**/*.{js,ts,jsx,tsx}"
],
theme: { extend: {} },
plugins: [],
};
styles/globals.css
@tailwind base;
@tailwind components;
@tailwind utilities;
3) Prisma schema (example)
prisma/schema.prisma
datasource db {
provider = "postgresql"
url = env("DATABASE_URL") // fallback/default tenant
}
generator client {
provider = "prisma-client-js"
}
model User {
id Int @id @default(autoincrement())
email String @unique
name String?
createdAt DateTime @default(now())
}
You can have separate DB URLs for each tenant (e.g. DATABASE_URL_TENANT1, DATABASE_URL_TENANT2, etc.) in .env.
4) Multi-tenant Prisma client
lib/prisma.ts
import { PrismaClient } from "@prisma/client";
type ClientMap = { [tenant: string]: PrismaClient };
const globalAny = global as any;
const clients: ClientMap = globalAny.__PRISMA_TENANT__ || {};
export function getPrisma(tenant: string) {
if (clients[tenant]) return clients[tenant];
// Build a per-tenant DB URL; fallback to DATABASE_URL if none
const envKey = `DATABASE_URL_${tenant.toUpperCase()}`;
const dbUrl = process.env[envKey] || process.env.DATABASE_URL;
clients[tenant] = new PrismaClient({
datasources: {
db: { url: dbUrl },
},
});
// Keep in global to reuse in dev mode (hot reload)
if (process.env.NODE_ENV !== "production") {
globalAny.__PRISMA_TENANT__ = clients;
}
return clients[tenant];
}
5) Middleware to rewrite subdomain
middleware.ts (in the project root)
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
export function middleware(req: NextRequest) {
const url = req.nextUrl.clone();
const host = req.headers.get("host") || "";
// Basic subdomain parsing (e.g. tenant1.example.com)
const [subdomain] = host.split(".");
const isLocalhost = host.startsWith("localhost");
if (!isLocalhost && subdomain && subdomain !== "www") {
// rewrite to /[tenant]/... so that Next.js catches the tenant param
url.pathname = `/${subdomain}${url.pathname}`;
return NextResponse.rewrite(url);
}
return NextResponse.next();
}
(If you want middleware to run only on certain paths, add export const config = { matcher: [...] }.)
6) Pages
pages/_app.tsx
import "../styles/globals.css";
import type { AppProps } from "next/app";
export default function MyApp({ Component, pageProps }: AppProps) {
return <Component {...pageProps} />;
}
pages/index.tsx (root “landing” when no subdomain)
export default function Home() {
return (
<div className="p-6">
<h1 className="text-2xl font-semibold">Default Site</h1>
<p>Visit a subdomain like tenant1.example.com to see tenant content.</p>
</div>
);
}
pages/[tenant]/index.tsx (multi-tenant route)
import { GetServerSideProps } from "next";
import { getPrisma } from "../../lib/prisma";
type Props = {
tenant: string;
users: { id: number; email: string; name: string | null }[];
};
export default function TenantPage({ tenant, users }: Props) {
return (
<div className="p-6">
<h1 className="text-xl font-semibold">Tenant: {tenant}</h1>
<ul className="mt-4 space-y-2">
{users.map((u) => (
<li key={u.id} className="border rounded p-3">
{u.email} {u.name ? `(${u.name})` : ""}
</li>
))}
</ul>
</div>
);
}
export const getServerSideProps: GetServerSideProps = async ({ params }) => {
const tenant = (params?.tenant as string) || "default";
const prisma = getPrisma(tenant);
// Example query for this tenant
const users = await prisma.user.findMany();
return { props: { tenant, users } };
};
7) Basic next.config.js (optional)
If you need to set experimental: { middlewarePrefetch: true } or other Next features, you can add them here. Otherwise, the default file is fine.
8) Example .env
DATABASE_URL="postgresql://user:pass@localhost:5432/default_db"
DATABASE_URL_TENANT1="postgresql://user:pass@localhost:5432/tenant1_db"
DATABASE_URL_TENANT2="postgresql://user:pass@localhost:5432/tenant2_db"
9) Run
- Generate the client:
npx prisma generate
- Migrate (for each tenant DB):
DATABASE_URL=... npx prisma migrate deploy
- Start dev server:
npm run dev
This skeleton rewrites requests based on the subdomain to a [tenant] page and instantiates a separate Prisma client (and pool) per tenant using the corresponding connection string. You can customize the pooling strategy (e.g., PgBouncer) or implement a more sophisticated cache if you have many tenants.