Security · Nov 21, 2026 · 11 min read

ReBAC with SpiceDB in Next.js: Fine-Grained Permissions

Discover how to implement relationship-based access control using SpiceDB in Next.js applications. This hands-on guide covers schema design for SaaS, TypeScript client integration, testing strategies,

ReBAC with SpiceDB in Next.js: Fine-Grained Permissions

The Limitations of Traditional Access Control Models

Most applications begin with simple role-based access control (RBAC). A user receives a role such as admin, editor, or viewer, and the system checks that role against a permission. This works for basic needs but collapses quickly in multi-tenant SaaS products with nested resources.

Consider a project management tool. A user might be an admin at the organization level, a guest on one project, and explicitly blocked from a specific task inside that project. Expressing "user X can view all tasks in projects they belong to except those marked private where they are not explicitly invited" requires either exploding the number of roles or moving authorization logic into application code. Both approaches create maintenance nightmares and security gaps.

Attribute-based access control (ABAC) improves flexibility by evaluating attributes at request time, but the evaluation rules become complex boolean expressions that are difficult to audit and test. Relationship-based access control (ReBAC) solves this by modeling the domain as a graph of resources and relations. Permissions are derived by traversing these relationships.

Google's Zanzibar paper formalized this model and powers authorization for Drive, Maps, Calendar, and Cloud. SpiceDB is the leading open-source implementation of the Zanzibar model, offering a consistent, low-latency permission service that scales to millions of relationships.

Core Concepts of the Zanzibar Model

Zanzibar stores authorization data as tuples in the form (resource, relation, subject). A concrete tuple might be:

(organization:acme#member, user:alice)
(project:mobile-app#parent, organization:acme)
(task:123#viewer, user:bob)
(task:123#parent, project:mobile-app)

Relations can reference other relations through usersets. For example, a schema can define that a project's viewer includes all members of its parent organization. Permission checks become recursive graph traversals that terminate when a direct subject match is found or the graph is exhausted.

SpiceDB adds three important capabilities beyond the original paper:

  • Caveats: Conditional logic attached to a relation (e.g., expiration timestamp).
  • Watch API: Real-time streaming of relationship changes.
  • Consistency options: Developers choose between minimal latency (minimum consistency) or guaranteed freshness (fully consistent) per request.

These features make SpiceDB suitable for production workloads where both developer experience and security guarantees matter.

Running SpiceDB Locally

Start with version 1.30.0, the current stable release as of late 2024. The fastest way to run SpiceDB locally is through Docker:

docker run \
  -p 8080:8080 \
  -p 50051:50051 \
  -e SPICEDB_DATASTORE_ENGINE=postgres \
  -e SPICEDB_DATASTORE_URI="postgres://postgres:password@localhost:5432/spicedb?sslmode=disable" \
  authzed/spicedb:v1.30.0 serve --grpc-preshared-key "dev-key"

You also need a PostgreSQL instance. For local development the docker-compose.yml below provides both services:

version: '3.8'
services:
  postgres:
    image: postgres:16
    environment:
      POSTGRES_PASSWORD: password
    ports:
      - "5432:5432"
  spicedb:
    image: authzed/spicedb:v1.30.0
    command: serve --grpc-preshared-key "dev-key" --datastore-engine postgres --datastore-uri "postgres://postgres:password@postgres:5432/spicedb?sslmode=disable"
    ports:
      - "8080:8080"
      - "50051:50051"
    depends_on:
      - postgres

Install the CLI tool zed (version 0.18.0 matches the server):

brew install authzed/tap/zed
# or
curl -L https://github.com/authzed/zed/releases/download/v0.18.0/zed_0.18.0_linux_x86_64.tar.gz | tar xz

Verify connectivity:

zed --insecure --endpoint localhost:50051 --token dev-key status

Schema Design for a SaaS Project Management Tool

A well-designed schema is the foundation of any ReBAC system. Create a file schema.zed with the following definition for an issue-tracking SaaS:

definition user {}

definition organization {
    relation member: user
    permission view = member
    permission admin = member
}

definition project {
    relation parent: organization
    relation owner: user
    relation member: user
    
    permission view = owner + member + parent->view
    permission edit = owner + member
    permission delete = owner
}

definition task {
    relation parent: project
    relation assignee: user
    relation creator: user
    
    permission view = creator + assignee + parent->view
    permission edit = creator + assignee + parent->edit
    permission delete = creator + parent->delete
}

This schema demonstrates several practical patterns:

  • Arrow operator (parent->view) inherits permissions from the parent resource.
  • Union operator (+) combines multiple relation paths.
  • Direct ownership relationships allow fine-grained exceptions to inherited permissions.

Apply the schema using the CLI:

zed schema write schema.zed

SpiceDB validates the schema for cycles and unreachable permissions during write. Schema changes are versioned; you can validate backward compatibility before deploying updates.

Integrating SpiceDB with Next.js

Install the official JavaScript client that works seamlessly with TypeScript:

npm install @authzed/authzed-node@0.12.0

Create a singleton client instance in lib/spicedb.ts:

import { v1 } from '@authzed/authzed-node';

const spicedb = v1.NewClient(
  process.env.SPICEDB_ENDPOINT || 'localhost:50051',
  process.env.SPICEDB_TOKEN || 'dev-key',
  v1.NewClientTokenMiddleware,
  { 
    transport: v1.Transport.Insecure,
    cache: { 
      enabled: true,
      size: 10000 
    }
  }
);

export default spicedb;

For production, replace the insecure transport with TLS and use short-lived tokens. Store the preshared key in Vercel or your platform's secret manager.

Permission Checks in Server Components and Route Handlers

Server Components are an ideal place to perform authorization because they run on the server and never expose sensitive logic to the client. Here is a concrete example for a task detail page:

import spicedb from '@/lib/spicedb';
import { v1 } from '@authzed/authzed-node';

export default async function TaskPage({ params }: { params: { id: string } }) {
  const session = await getServerSession();
  if (!session?.user?.id) {
    redirect('/login');
  }

  const checkRequest = v1.CheckPermissionRequest.create({
    consistency: v1.Consistency.create({
      requirement: {
        oneofKind: 'fullyConsistent',
        fullyConsistent: true
      }
    }),
    resource: v1.ObjectReference.create({
      objectType: 'task',
      objectId: params.id
    }),
    permission: 'view',
    subject: v1.SubjectReference.create({
      object: v1.ObjectReference.create({
        objectType: 'user',
        objectId: session.user.id
      })
    })
  });

  const response = await spicedb.checkPermission(checkRequest);
  
  if (response.permissionship !== v1.CheckPermissionResponse_Permissionship.HAS_PERMISSION) {
    notFound();
  }

  const task = await db.task.findUnique({ where: { id: params.id } });
  return <TaskDetail task={task} />;
}

The fullyConsistent option guarantees the check reflects all writes that occurred before the request. For high-traffic read paths, switch to minimizeLatency and accept a small staleness window (typically <100ms).

Writing Relationships When Resources Are Created

Creating a resource must be an atomic operation with its relationship tuples. Use a database transaction and SpiceDB write in the same request:

async function createTask(data: CreateTaskInput, userId: string) {
  return await db.$transaction(async (tx) => {
    const task = await tx.task.create({
      data: {
        title: data.title,
        projectId: data.projectId,
        creatorId: userId,
        assigneeId: data.assigneeId
      }
    });

    const writes = [
      // Task belongs to project
      v1.RelationshipUpdate.create({
        operation: v1.RelationshipUpdate_Operation.TOUCH,
        relationship: v1.Relationship.create({
          resource: v1.ObjectReference.create({ objectType: 'task', objectId: task.id }),
          relation: 'parent',
          subject: v1.SubjectReference.create({
            object: v1.ObjectReference.create({ objectType: 'project', objectId: data.projectId })
          })
        })
      }),
      // Creator can view and edit
      v1.RelationshipUpdate.create({
        operation: v1.RelationshipUpdate_Operation.TOUCH,
        relationship: v1.Relationship.create({
          resource: v1.ObjectReference.create({ objectType: 'task', objectId: task.id }),
          relation: 'creator',
          subject: v1.SubjectReference.create({
            object: v1.ObjectReference.create({ objectType: 'user', objectId: userId })
          })
        })
      })
    ];

    await spicedb.writeRelationships({
      updates: writes
    });

    return task;
  });
}

The TOUCH operation creates the relationship if it does not exist or updates it if it does. This idempotency is crucial for retry-safe operations.

Advanced Schema Patterns: Caveats and Exclusion

SpiceDB 1.30 supports caveats — lightweight conditions evaluated at check time. Extend the task definition to support temporary access:

definition task {
    ...
    relation temporary_viewer: user with expiration
    
    permission view = creator + assignee + temporary_viewer
}

caveat expiration(expiration_timestamp: int64) {
    expiration_timestamp > context.now
}

When writing the relationship, attach contextual parameters:

v1.RelationshipUpdate.create({
  operation: v1.RelationshipUpdate_Operation.TOUCH,
  relationship: v1.Relationship.create({
    resource: ...,
    relation: 'temporary_viewer',
    subject: v1.SubjectReference.create({ ... }),
    caveat: v1.Caveat.create({
      caveatName: 'expiration',
      context: { expiration_timestamp: Date.now() + 3600000 }
    })
  })
})

Exclusion relationships allow explicit blocks. For example, a user can be a project member but explicitly denied access to one sensitive task using an excluded_viewer relation combined with set difference in the permission definition.

Testing Authorization Logic

SpiceDB supports a declarative test format. Create tests.yaml:

schema: schema.zed
relationships:
  - "organization:acme#member@user:alice"
  - "project:mobile#parent@organization:acme"
  - "task:123#parent@project:mobile"
  - "task:123#creator@user:bob"
assertions:
  - check:
      resource: task:123
      permission: view
      subject: user:alice
    expected: true
  - check:
      resource: task:123
      permission: edit
      subject: user:bob
    expected: true

Run the test suite with:

zed test tests.yaml

Integrate these tests into your CI pipeline. Because the test file is data, non-developers can review permission requirements before shipping features.

Production Deployment Considerations

For production, run SpiceDB on Kubernetes using the official Helm chart:

helm repo add authzed https://charts.authzed.com
helm install spicedb authzed/spicedb --set datastore.engine=postgres

Configure at least three replicas for high availability. Use a dedicated PostgreSQL cluster with high IOPS because SpiceDB is write-heavy during relationship updates.

Connection management in Next.js is critical. The JavaScript client maintains its own connection pool, but you should create one client instance per server and reuse it across requests. For serverless platforms like Vercel, use a managed SpiceDB service such as Authzed Dedicated or Cloud to avoid cold-start latency.

Enable the metrics endpoint (--http-enabled) and collect the following key metrics:

  • spicedb_check_count
  • spicedb_dispatch_count
  • spicedb_relationship_write_latency

Configure alerts when p99 check latency exceeds 15ms.

Performance Trade-offs and Caching

SpiceDB achieves low latency through aggressive caching and a distributed dispatch architecture. A typical permission check on a properly indexed schema completes in 3-8 milliseconds. However, complex userset recursion can increase dispatch count and latency.

You can add a local cache layer in your Next.js application using Upstash Redis or Vercel KV for repeated checks within the same request context. Never cache across different users without including the subject in the cache key. For most SaaS workloads, the following pattern works well:

const cacheKey = `perm:${resourceType}:${resourceId}:${permission}:${userId}`;
const cached = await kv.get(cacheKey);
if (cached !== null) return cached === '1';

Set a short TTL (30-60 seconds) and use SpiceDB's consistency tokens to invalidate cache entries when relationships change via the Watch API.

Migrating Existing RBAC Systems

Most teams cannot replace their authorization system in one pull request. A practical migration path starts by running SpiceDB alongside your existing RBAC implementation. Begin by mirroring role assignments into relationship tuples using background workers. Once confidence in the new model is established, route permission checks to SpiceDB for new features first.

Use SpiceDB's lookupResources and lookupSubjects APIs to power "list all tasks I can view" queries instead of complex SQL filters. This approach often improves query performance dramatically because the permission graph is optimized for traversal rather than relational joins.

Common Pitfalls and Solutions

Several recurring issues appear when adopting ReBAC:

  1. Overly deep relationship graphs: Keep inheritance depth under five levels. Deeper graphs increase dispatch count and latency. Flatten where possible.
  2. Using ReBAC for data that changes frequently: Relationship writes are more expensive than permission checks. If a permission depends on a mutable attribute (e.g., "task is not completed"), consider moving that to a caveat instead of updating tuples on every status change.
  3. Inconsistent consistency choices: Mixing fullyConsistent and minimizeLatency in the same user flow can produce surprising results. Document consistency requirements per endpoint.
  4. Schema evolution without compatibility checks: Always run zed schema validate with the --force flag disabled before applying changes in production.

Address these by maintaining a permission architecture decision record (ADR) that documents the rationale for each relation and permission definition.

Observability and Auditing

SpiceDB emits structured logs and OpenTelemetry traces. Configure your Next.js application to propagate trace context so a single user request can be correlated with the permission checks it triggered. This is invaluable when debugging "why can't this user see this task" issues.

For compliance-sensitive applications, enable SpiceDB's audit logging feature to capture every check and write with full context. These logs can be streamed to your SIEM or data lake.

The combination of SpiceDB's audit capabilities and Next.js server component logging creates a complete authorization trail without scattering console.log statements throughout your codebase.

Scaling to Millions of Relationships

SpiceDB scales horizontally by adding more nodes. The datastore (PostgreSQL, CockroachDB, or Spanner) becomes the primary bottleneck at very high scale. At tens of millions of relationships, consider CockroachDB for its distributed SQL capabilities.

Relationship sharding and careful schema design prevent hot spots. The official documentation provides benchmark numbers showing a single node handling thousands of checks per second with sub-10ms latency on modest hardware. For most startups, a single properly configured SpiceDB node with a managed Postgres instance is sufficient until reaching significant scale.

The decoupled nature of SpiceDB means your Next.js application remains responsive even during permission system maintenance. This separation of concerns is one of the strongest arguments for adopting a dedicated authorization service rather than embedding complex permission logic inside your application or database row-level security policies.

By modeling your domain as relationships and leveraging SpiceDB's type system, you create authorization logic that is both understandable by non-engineers and enforceable at scale. The initial investment in schema design pays dividends as new features are added without touching core permission code.

Keep reading

Related Articles