saas-multi-tenant
できること
このツールは、複数の顧客(「テナント」と呼ばれます)が同じデータベースを安全に共有するアプリケーションを作るのに役立ちます。それぞれの顧客は、自分のデータだけを見られるようになります。
使う場面
- ✓複数の顧客向けにSaaSアプリケーションを作るとき。
- ✓顧客ごとにデータを分離する必要があるとき。
- ✓顧客同士が互いのデータを見られないようにセキュリティを実装するとき。
スキルのリンク
https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/saas-multi-tenant/SKILL.mdコピーしてAI(Claude、ChatGPT、Cursor)に貼り付け、指示に従うよう頼んでください。
使い方
いちばん簡単な方法:メッセージをコピーしてAIに貼り付けるだけ。AIがスキルを読んで指示に従います。
貼り付け用メッセージ
Claude Code、Codex、Cursorの場合:プロジェクトのフォルダで実行するとスキルがインストールされます。
SKILL.mdをダウンロードして、エージェントのスキル用フォルダに入れてください。
AIへの頼み方の例
“SaaSアプリで、ある顧客のデータが別の顧客から見られないようにするにはどうすればよいですか?”
毎週5つの新しいスキル。1分で読めます。
仕組み
各テーブルに顧客IDの列を追加するようデータベースを設定し、セキュリティルールを使ってデータを自動的に絞り込みます。また、リクエストごとにどの顧客がデータにアクセスしているかを判断する「ミドルウェア」も作成します。
技術的な内容(元のSKILL.md)
作者による元のテキスト(英語)をGitHubからそのまま表示しています。
SaaS Multi-Tenant Architecture
When to Use This Skill
- The user is building a SaaS application where multiple customers share the same database
- The user asks about tenant isolation, row-level security, or data leakage prevention
- The user needs to scope every database query to a specific tenant without manual WHERE clauses
- The user asks about shared-schema vs schema-per-tenant vs database-per-tenant tradeoffs
- The user is implementing admin endpoints that must access data across tenants
- The user needs to add
tenant_idcolumns to an existing single-tenant application - The user asks about PostgreSQL RLS policies for tenant isolation
- The user is building tenant-aware middleware in Express, Fastify, or Next.js API routes
Do NOT use this skill when:
- The user is building a single-user application with no shared infrastructure
- The user asks about authentication only without tenant scoping (use an auth skill instead)
- The user needs general database schema design without multi-tenancy requirements
Core Workflow
Determine the tenancy model. Ask the user about their scale expectations and isolation requirements. For most SaaS apps under 1000 tenants, shared-schema with a
tenant_idcolumn on every table is the correct default. Schema-per-tenant adds operational overhead (migrations run N times). Database-per-tenant is only justified when tenants have regulatory data residency requirements.Add
tenant_idto every tenant-scoped table. The column must beNOT NULL, typeUUIDorTEXT, and included in every composite index. Never allow a tenant-scoped table to exist without this column — a missingtenant_idis a data leak waiting to happen.Set up PostgreSQL Row-Level Security (RLS). Create a policy on each tenant-scoped table that filters rows by
current_setting('app.current_tenant_id'). This acts as a database-level safety net — even if application code forgets a WHERE clause, RLS blocks cross-tenant reads.Build tenant-aware middleware. At the start of every request, extract the
tenant_idfrom the authenticated session or JWT claims. Set it on the database connection usingSET LOCAL app.current_tenant_id = '...'inside a transaction. Every subsequent query in that request inherits the tenant scope automatically.Scope all ORM queries by tenant. If using Prisma, apply a global middleware that injects
where: { tenantId }into everyfindMany,findFirst,update, anddeletecall. If using Drizzle, create a base query builder that includes the tenant filter. Never rely on developers remembering to add the filter manually.Handle tenant-aware migrations. Every new table migration must include
tenant_idas a column. Write a linting rule or CI check that rejects any migration creating a table withouttenant_idunless the table is explicitly marked as global (e.g.,plans,feature_flags).Build cross-tenant admin routes separately. Admin endpoints that aggregate data across tenants must bypass RLS explicitly using
SET LOCAL role = 'admin_bypass'or a dedicated database role. These routes must be protected by a separate admin authentication flow — never reuse tenant user sessions for admin access.Implement tenant provisioning. When a new customer signs up, create their tenant record, seed default data (roles, settings, onboarding state), and assign the founding user. Wrap this in a database transaction so partial provisioning never leaves orphan records.
Examples
Example 1: PostgreSQL RLS Policy for Tenant Isolation
-- Enable RLS on the table
ALTER TABLE projects ENABLE ROW LEVEL SECURITY;
ALTER TABLE projects FORCE ROW LEVEL SECURITY;
-- Policy: users can only see rows where tenant_id matches the session variable
CREATE POLICY tenant_isolation ON projects
USING (tenant_id = current_setting('app.current_tenant_id')::uuid);
-- Policy for INSERT: new rows must match the current tenant
CREATE POLICY tenant_insert ON projects
FOR INSERT
WITH CHECK (tenant_id = current_setting('app.current_tenant_id')::uuid);
Example 2: Express Middleware That Sets Tenant Context per Request
import { Pool } from "pg";
const pool = new Pool({ connectionString: process.env.DATABASE_URL });
async function tenantMiddleware(req, res, next) {
const tenantId = req.auth?.tenantId; // extracted from JWT during auth
if (!tenantId) return res.status(403).json({ error: "No tenant context" });
…
よくある質問
「テナント」とは何ですか?
SaaSアプリケーションを利用する個々の顧客のことです。100社がソフトウェアを使っていれば、テナントは100あることになります。
なぜ共有データベースを使うのですか?
顧客ごとに別々のデータベースを用意するより、コストを抑えられ、管理も簡単です。特に顧客数が多い場合に効果的です。
「行レベルセキュリティ」(RLS)とは何ですか?
データベースのセキュリティ機能の一つで、各ユーザーや顧客が、自分に属する行(レコード)だけを閲覧・変更できるようにするものです。
詳細
作者による元の説明
Design and implement multi-tenant SaaS architectures with row-level security, tenant-scoped queries, shared-schema isolation, and safe cross-tenant admin patterns in PostgreSQL and TypeScript.
人気
- GitHubのスター
- 48k
- ランキング
- #5655
- ライセンス
- MIT
- 更新日
- 2026/10/15
コメント
- …
このリポジトリの他のスキル
00-andruia-consultant
48kエージェントがAIプロジェクトの立ち上げや改善を支援します。コードを分析し、ツールを提案し、スペイン語で行動計画を作成します。
007
48kエージェントがセキュリティ監査と脅威モデリングを行えるようにします。攻撃や脆弱性からプロジェクトを守るのに役立ちます。
10-andruia-skill-smith
48kエージェントがAIツールの作成や改善を支援します。ツールの動作を定義し、ドキュメントを書き、構造を検証します。
20-andruia-niche-intelligence
48kエージェントが特定の業界に関する要約を作成できるようにします。信頼できる情報源を使って、プロジェクトの背景、ルール、利用パターン、リスクを把握するのに役立ちます。
似ているスキル
api-connector-builder
280kエージェントが既存のパターンに従って、新しいAPI連携を構築します。新しい方式を作らずに、もう一つ連携を追加したいときに使います。
api-design
280kエージェントがベストプラクティスに沿ってREST APIを設計できるようにします。APIの通信方法、エラーの表示方法、データの整理方法を決めるのに役立ちます。
backend-patterns
280kエージェントのサーバーサイドのアーキテクチャパターンとデータベースの最適化を支援します。サーバー上で動くコードを作成またはレビューするときに役立ちます。