Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

Sorry, you do not have permission to ask a question, You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please type your username.

Please type your E-Mail.

Please choose an appropriate title for the post.

Please choose the appropriate section so your post can be easily searched.

Please choose suitable Keywords Ex: post, video.

Browse

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Navigation

  • Home
  • About Us
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • About Us
  • Contact Us
Home/ Questions/Q 1882

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Latest Questions

Author
  • 62k
Author
Asked: November 26, 20242024-11-26T12:16:07+00:00 2024-11-26T12:16:07+00:00

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

  • 62k

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);       });     });     setAbility(newAbility);   }    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 (     <div>       <p>Permission Test</p>       <Can I="create" a="doc" ability={ability}>         <div>You can see this if you have 'create:doc' permission</div>       </Can>       <Can I="manage" a="money" ability={ability}>         <div>This will not render unless you have 'manage:money' permission</div>       </Can>     </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.

casljotainextjswebdev
  • 0 0 Answers
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

Sidebar

Ask A Question

Stats

  • Questions 4k
  • Answers 0
  • Best Answers 0
  • Users 2k
  • Popular
  • Answers
  • Author

    How to ensure that all the routes on my Symfony ...

    • 0 Answers
  • Author

    Insights into Forms in Flask

    • 0 Answers
  • Author

    Kick Start Your Next Project With Holo Theme

    • 0 Answers

Top Members

Samantha Carter

Samantha Carter

  • 0 Questions
  • 20 Points
Begginer
Ella Lewis

Ella Lewis

  • 0 Questions
  • 20 Points
Begginer
Isaac Anderson

Isaac Anderson

  • 0 Questions
  • 20 Points
Begginer

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help

Footer

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore, ask, and connect. Join our vibrant Q&A community today!

About Us

  • About Us
  • Contact Us
  • All Users

Legal Stuff

  • Terms of Use
  • Privacy Policy
  • Cookie Policy

Help

  • Knowledge Base
  • Support

Follow

© 2022 Querify Question. All Rights Reserved

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.