DEV Community

Alex T.
Alex T.

Posted on

An elegant way to use CASL, Jotai for Permission Control on Next.JS

In the case of combining CASL with Next.js (a React framework), the common solution is to employ React's Context API. However, this approach can lead to hydration issues in Next.js, which may force a fallback to client-side rendering, undermining the benefits of Next.js's server-side capabilities. To address this, we've explored an alternative using Jotai, which has proven to be a cleaner and more efficient solution.

The Advantages of Using Jotai Over Context API

Jotai presents a couple of significant advantages over the traditional Context API:

  1. Performance: Jotai boosts performance by re-rendering only the components that are subscribed to a specific piece of state. In contrast, the Context API causes all consumer components to re-render whenever there's a change in the context, leading to potential performance bottlenecks in larger applications.

  2. Simplicity: With Jotai, there's no need to set up a provider component, which streamlines the codebase and simplifies state management.

Our Tech Stack

Before diving into the implementation details, here's a quick overview of our tech stack:

  • CASL version 6
  • Next.js version 14
  • Jotai version 2.6

The custom hook we'll discuss is useAbility, found in src/hooks/users/use-permission.ts.

The useAbility Hook

Let's take a look at what our useAbility hook looks like:

import { useAtom, atom } from 'jotai';
import { Ability, defineAbility } from '@casl/ability';

type PermissionStrings = string[];
const abilityAtom = atom<Ability>(defineAbility(() => {}));

export function useAbility() {
  const [ability, setAbility] = useAtom(abilityAtom);

  function buildAbilityFromString(permissionStrings: PermissionStrings): void {
    const permissions = permissionStrings.flat();
    const newAbility = defineAbility((can) => {
      permissions.forEach((permission) => {
        const [action, subject] = permission.split(':');
        can(action, subject);

  return { ability, buildAbilityFromString };
Enter fullscreen mode Exit fullscreen mode

In this hook, we're using Jotai's atom and useAtom to manage our CASL Ability instance. The buildAbilityFromString function allows us to dynamically construct abilities from a list of permission strings.

How to Use useAbility in Components

To leverage the useAbility hook in your components, follow these steps:

  1. At the beginning of your component file, use the use client; directive to ensure the code runs on the client side.
  2. Import the useAbility hook and the Can component from CASL's React package:
import { useAbility } from '@/hooks/users/use-permission';
import { Can } from '@casl/react';
Enter fullscreen mode Exit fullscreen mode
  1. Invoke the useAbility hook within your component to get the ability instance:
const { ability } = useAbility();
Enter fullscreen mode Exit fullscreen mode
  1. Use the Can component to control the rendering based on permissions:
"use client";
import React from "react";
import { useAbility } from "@/hooks/users/use-permission";
import { Can } from "@casl/react";

const PermissionTestComp = () => {
  const { ability } = useAbility();

  return (
      <p>Permission Test</p>
      <Can I="create" a="doc" ability={ability}>
        <div>You can see this if you have 'create:doc' permission</div>
      <Can I="manage" a="money" ability={ability}>
        <div>This will not render unless you have 'manage:money' permission</div>

export default PermissionTestComp;
Enter fullscreen mode Exit fullscreen mode

By following this approach, you can ensure that your Next.js application benefits from both server-side rendering and client-side authorization checks, without running into the common hydration issues associated with the Context API.

Note: If there are any errors in the article, please feel free to point them out. Thank you.

Top comments (0)