CASL Svelte

@casl/svelte

@casl/svelte NPM version Support

This package allows to integrate CASL with Svelte application. So, you can show or hide UI elements based on user ability to see them.

Installation

npm install @casl/svelte @casl/ability
# or
yarn add @casl/svelte @casl/ability
# or
pnpm add @casl/svelte @casl/ability

Important: requires svelte: ^5.7.0

Provide an Ability

To provide an ability just define your application Ability types:

import { createMongoAbility, type MongoAbility, type RawRuleOf } from '@casl/ability';

export type AppAbility = MongoAbility<['read' | 'update', 'Article']>;

export type AppRule = RawRuleOf<AppAbility>[];
export const createAppAbility = (rules: AppRule[]) =>  createMongoAbility<AppAbility>(rules);

Then use provideAbility in the root component. The returned value of this function is a reactive adapter around the supplied Ability.

<script lang="ts">
  import { untrack } from 'svelte';
  import { provideAbility } from '@casl/svelte';
  import { createAppAbility, type AppRule } from './AppAbility.ts';
  import ArticleActions from './ArticleActions.svelte';

  let { initialRules }: { initialRules: AppRule[] } = $props();
  const ability = createAppAbility(untrack(() => initialRules));
  const { update: updateAbility } = provideAbility(ability);
</script>

<ArticleActions />
<button onclick={() => updateAbility([])}>Clear permissions</button>

untrack makes the initial rules capture explicit; later prop changes require an explicit refresh as described below.

Each call to provideAbility creates one Ability adapter. All descendants share that same adapter through context.

Check permissions

Use useAbility<AppAbility>() during component initialization. Use native Svelte {#if} blocks for conditional UI:

<!-- ArticleActions.svelte -->
<script lang="ts">
  import { useAbility } from '@casl/svelte';
  import type { AppAbility } from './AppAbility.ts';

  const { can, cannot, relevantRuleFor, update: updateAbility } = useAbility<AppAbility>();
  const denialReason = $derived(
    cannot('update', 'Article')
      ? relevantRuleFor('update', 'Article')?.reason
      : undefined
  );
</script>

{#if can('read', 'Article')}
  <a href="/articles">Read articles</a>
{/if}
{#if can('update', 'Article', 'title')}
  <a href="/articles/edit">Edit title</a>
{/if}
{#if denialReason}
  <p>{denialReason}</p>
{/if}
<button onclick={() => updateAbility([])}>Clear permissions</button>

We can either share AppAbility with consumers to preserve action, subject, field, update rule, and returned rule types or create a small wrapper around it - useAppAbility().

Update and refresh permissions

By either updating Ability adapter or Ability itself, it will cause svelte to re-render affected components. Choose whatever is better from application perspective.

// In the provider component, after creating ability and permissions:
function refreshPermissions(rules: AppRules) {
  ability.update(rules);
}

function clearPermissions() {
  permissions.update([]);
}

Reactivity and cleanup

All methods of Ability adapter except of update are reactive. So, whenever you use them in components, those components will automatically subscribe to Ability updates, including both views and $derived runes.

Each adapter shares a single listener while it has tracked readers, even when many descendants call useAbility. The listener is removed after the last reader is destroyed. Readers that become active again see current rules. Calls outside reactive computations read current permissions without creating persistent subscriptions.

Server rendering and SvelteKit

Create a separate Ability for each request or independent render tree and call provideAbility during component initialization on both the server and client. A mutable, user-specific module singleton may be shared by server requests and expose one user's authorization state to another. Export createAppAbility and create each instance within its request or component tree instead. See SvelteKit's guidance on avoiding shared state on the server.

For hydration, reconstruct the client Ability from permission inputs equivalent to those used for server rendering. Equivalent rules, matchers, subject resolution, and checked data must yield equivalent initial permission results. Initialize the provider before rendering permission-dependent UI on either side.

SvelteKit may retain layouts across navigation. When permission data changes, explicitly update the retained Ability through the application's refresh flow, or remount its provider when replacing the instance. Initializing from a prop once does not synchronize later prop changes.