Saltar al contenido
Skillpedia
APIs y servidores (backend)48 mil · #5655

saas-multi-tenant

Qué hace

Esta herramienta te ayuda a crear aplicaciones en las que varios clientes (o "tenants") comparten de forma segura la misma base de datos. Se asegura de que cada cliente solo vea sus propios datos.

Cuándo usarla

  • ✓Cuando creas una aplicación SaaS para varios clientes.
  • ✓Cuando necesitas aislar los datos de cada cliente.
  • ✓Cuando implementas seguridad para que los clientes no vean los datos de los demás.

Link de la skill

https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/saas-multi-tenant/SKILL.md

Cópialo y pégalo en tu IA (Claude, ChatGPT o Cursor) pidiéndole que siga las instrucciones.

Cómo usar

La forma más fácil: copia el mensaje y pégalo en tu IA. Ella lee la skill y sigue las instrucciones.

Mensaje listo para pegar

Usa esta skill para ayudarme: https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/saas-multi-tenant/SKILL.md Lee el archivo SKILL.md de ese link y sigue sus instrucciones en mi tarea.
¿Quieres que tu IA encuentre skills como esta por sí sola?Instala el MCP gratis de Skillpedia: una línea, y busca entre 15.000+ skills antes de cada tarea.Instalar en 1 minuto →

Ejemplo de qué pedirle a la IA

“¿Cómo puedo asegurarme de que los datos de un cliente no los vea otro en mi aplicación SaaS?”

5 skills nuevas por semana. 1 minuto de lectura.

Cómo funciona

Configura la base de datos para añadir una columna con el ID del cliente en cada tabla y usa reglas de seguridad que filtran los datos de forma automática. También crea un "middleware" que define qué cliente está accediendo a los datos en cada petición.

Contenido técnico (SKILL.md original)

Texto original del autor, en inglés, directo de 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_id columns 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

  1. 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_id column 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.

  2. Add tenant_id to every tenant-scoped table. The column must be NOT NULL, type UUID or TEXT, and included in every composite index. Never allow a tenant-scoped table to exist without this column — a missing tenant_id is a data leak waiting to happen.

  3. 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.

  4. Build tenant-aware middleware. At the start of every request, extract the tenant_id from the authenticated session or JWT claims. Set it on the database connection using SET LOCAL app.current_tenant_id = '...' inside a transaction. Every subsequent query in that request inherits the tenant scope automatically.

  5. Scope all ORM queries by tenant. If using Prisma, apply a global middleware that injects where: { tenantId } into every findMany, findFirst, update, and delete call. If using Drizzle, create a base query builder that includes the tenant filter. Never rely on developers remembering to add the filter manually.

  6. Handle tenant-aware migrations. Every new table migration must include tenant_id as a column. Write a linting rule or CI check that rejects any migration creating a table without tenant_id unless the table is explicitly marked as global (e.g., plans, feature_flags).

  7. 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.

  8. 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" });


…
Preguntas frecuentes

¿Qué es un "tenant"?

Un "tenant" es un cliente individual de tu aplicación SaaS. Si tienes 100 clientes usando tu software, tienes 100 tenants.

¿Por qué usar una base de datos compartida?

Es más económica y más fácil de gestionar que tener una base de datos separada para cada cliente, sobre todo cuando tienes muchos clientes.

¿Qué es la "seguridad a nivel de fila" (RLS)?

Es una función de seguridad de la base de datos que garantiza que cada usuario o cliente solo pueda ver o modificar las filas (registros) que le pertenecen.

Detalles

Descripción original del autor

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.

repo: sickn33/agentic-awesome-skills

Popularidad

Estrellas en GitHub
48 mil
Posición en el ranking
#5655
Licencia
MIT
Actualizada
15/10/2026

¿Te sirve esta skill?

0

Entra para votar.

Comentarios

  • …

Más skills de este repositorio

Skills parecidas