Dyrecteddyrected
Recipes

Restrict Content Operations by User Role

Express least-privilege operation rules in server configuration.

Role checks belong in collection or field access functions, not only in navigation or button rendering.

Allow public reads, editor writes, and administrator deletion with collection access rules.

Use this when

  • only editors can update content
  • restrict deletion to admins
  • make content publicly readable
  • add role based access

Dyrected concepts

access, AuthenticatedUser, roles

Additional packages: No additional packages.

Complete recipe

This is the canonical source compiled and behavior-tested by @dyrected/knowledge.

import { defineCollection, defineTextField } from "@dyrected/core";

export const Articles = defineCollection({
  slug: "articles",
  access: {
    read: () => true,
    create: ({ user }) => user?.roles?.some((role) => role === "editor" || role === "admin") ?? false,
    update: ({ user }) => user?.roles?.some((role) => role === "editor" || role === "admin") ?? false,
    delete: ({ user }) => user?.roles?.includes("admin") ?? false,
  },
  fields: [defineTextField({ name: "title", label: "Title", required: true })],
});

Decisions and cautions

  • Treat roles on the authenticated server user as trusted only if clients cannot assign them to themselves.
  • Grant each operation independently; edit permission should not imply delete or publish permission.
  • Test unauthenticated users and unknown roles.
  • Prefer capabilities when rules become more granular than a few stable roles.

Public read access exposes every readable field unless field-level access removes it. Audit sensitive fields separately.

On this page