@cerbos/react
TypeScript icon, indicating that this package has built-in type declarations

0.1.4 • Public • Published

@cerbos/react

npm

A collection of React hooks for interacting with Cerbos policy decision points.

Prerequisites

  • Cerbos 0.16+
  • React 16.13+

Installation

$ npm install @cerbos/react

Example usage

First, create an HTTP or embedded Cerbos client, and provide it to your application's components using CerbosProvider:

import { Embedded as Cerbos } from "@cerbos/embedded";
// or, import { HTTP as Cerbos } from "@cerbos/http";
import { CerbosProvider } from "@cerbos/react";

const client = new Cerbos();

function MyApp({ children }) {
  const user = useYourAuthenticationLogic(...);

  return (
    <CerbosProvider
      client={client}
      principal={
        user
          ? {
              id: user.id,
              roles: user.roles,
            }
          : {
              // Define an arbitrary ID for unauthenticated users.
              id: "###ANONYMOUS_USER###",
              // Define a role that represents unauthenticated users (at least one is required).
              roles: ["anonymous"],
            }
      }
    >
      {children}
    </CerbosProvider>
  );
}

Then, use the client to perform permission checks in your components, using one of the provided hooks:

import { useIsAllowed } from "@cerbos/react";

function SomeComponent() {
  const check = useIsAllowed({
    resource: {
      kind: "document",
      id: "1",
      attr: { owner: "user@example.com" },
    },
    action: "view",
  });

  if (check.isLoading) {
    // show spinner
    return "Loading...";
  }

  if (check.error) {
    // handle error
    return "Error...";
  }

  return <div>{check.data && <button>a button document 1</button>}</div>;

Further reading

Get help

Package Sidebar

Install

npm i @cerbos/react

Weekly Downloads

142

Version

0.1.4

License

Apache-2.0

Unpacked Size

49.4 kB

Total Files

22

Last publish

Collaborators

  • cerbosdev