Communitygithub.com

YepAPI/skills

租户隔离(行级与Schema级)、子域名路由、每个租户的配置以及数据分区。

skills 是什么?

该技能描述了实现多租户架构的完整方案,涵盖了从基本的行级隔离到高级的Schema隔离、子域名路由、自定义域名映射以及每个租户的配置管理。它明确了数据隔离、路由和配置管理的规则,并提供了使用 Prisma 中间件实现自动 `tenantId` 过滤以及 Next.js 中间件进行子域名解析的 TypeScript 代码示例。此技能对于任何需要构建多租户 SaaS 应用的开发者都极具价值,能够防止跨租户数据泄露,同时通过按 `tenantId` 分区来优化查询性能。它支持 Prisma 和 Next.js 等常见平台和框架。

兼容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/YepAPI/skills/tree/HEAD/skills/multi-tenancy

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

多租户

规则

  • 行级隔离(默认):在每个租户范围内的表中添加 tenantId 列,并通过中间件或 RLS(行级安全)强制执行。
  • 每个租户一个 Schema:当租户需要自定义 Schema 或严格数据隔离时使用。操作更复杂,但隔离性更好。
  • 子域名路由:从 {tenant}.app.com 中解析租户。在中间件中解析,并将 tenantId 设置在请求上下文中。
  • 自定义域名:将 CNAME 指向您的应用,通过 Host 标头查找租户。使用 domains 表将自定义域名映射到租户 ID。
  • 每租户配置:将主题(Logo、颜色)、功能标志和限制存储在 tenant_settings 表中,并在内存中缓存(带 TTL)。
  • RLS 模式 (Postgres):ALTER TABLE posts ENABLE ROW LEVEL SECURITY; CREATE POLICY tenant_isolation ON posts USING (tenant_id = current_setting('app.tenant_id'))
  • 中间件:从子域名/标头提取租户,设置到上下文中,并应用于所有数据库查询——绝不允许查询在没有租户范围的情况下运行。
  • 数据分区:对于大型表,按 tenantId 分区——可提高查询性能,并支持按租户进行备份/恢复。

行级隔离模式

// 中间件 - 从子域名解析租户
function getTenantFromHost(host: string): string {
  const subdomain = host.split(".")[0];
  return subdomain; // 或在 tenants 表中查找
}

// Prisma 中间件 - 自动按 tenantId 过滤
prisma.$use(async (params, next) => {
  if (TENANT_MODELS.includes(params.model)) {
    params.args.where = { ...params.args.where, tenantId: context.tenantId };
  }
  return next(params);
});

子域名路由 (Next.js 中间件)

export function middleware(request: NextRequest) {
  const host = request.headers.get("host") ?? "";
  const tenant = host.split(".")[0];
  const response = NextResponse.next();
  response.headers.set("x-tenant-id", tenant);
  return response;
}

避免

  • 没有租户范围的查询——缺少 WHERE tenantId = ? 会跨租户泄露数据
  • 在客户端硬编码租户——应从服务器端子域名/域名解析
  • 没有 tenantId 索引——每个租户范围内的表都需要一个以 tenantId 开头的复合索引
  • 在共享缓存中混合租户数据——使用 {tenantId}:{key} 命名空间化缓存键

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

YepAPI/skills

WCAG 2.1 AA — semantic HTML, keyboard navigation, screen readers.

YepAPI/skills

Experiment setup, variant splitting, statistical significance, and feature flag integration.

YepAPI/skills

CRUD generators, data tables, user management, role-based access, and bulk operations.

YepAPI/skills

Monitor what ChatGPT and Gemini say about your brand using YepAPI.

YepAPI/skills

Queue workers with BullMQ/Inngest/Trigger.dev, job retries, dead letter queues, concurrency.

YepAPI/skills

Commander.js, interactive prompts with Clack, spinners, colors, config files, exit codes, and npm publishing.

YepAPI/skills

cmdk integration, Cmd+K trigger, fuzzy search, grouped actions, keyboard navigation, and dynamic action registration.

YepAPI/skills

Content planning with trend and sentiment data from YepAPI.

YepAPI/skills

Content calendar, keyword-driven planning, and content briefs.

YepAPI/skills

Theme switching with CSS variables, system preference detection, next-themes, and persistence.

YepAPI/skills

Threaded comments, @mentions, reactions, moderation queue, optimistic UI, and cursor pagination.

YepAPI/skills

Competitive analysis between domains using YepAPI.

YepAPI/skills

Layout grids, KPI cards, data tables with sorting/filtering, sidebar navigation, and responsive breakpoints.

YepAPI/skills

Data encryption — TLS everywhere, AES-256-GCM for PII, bcrypt passwords, encrypted backups.

YepAPI/skills

Chart patterns with Recharts/Nivo/D3, responsive containers, color scales, and accessibility.

YepAPI/skills

Drizzle schema definition, push vs migrate, type-safe queries, relations, transactions, and prepared statements.

YepAPI/skills

Upload handling, resize/compress, CDN delivery, blur placeholders, and next/image patterns.

YepAPI/skills

Local business and Google Maps research using YepAPI.

YepAPI/skills

Cursor-based pagination, IntersectionObserver, virtualized lists with @tanstack/react-virtual, and scroll position restoration.

YepAPI/skills

Chat UI components, streaming responses with AI SDK, context window management, and RAG patterns.

相关技能