{"id":18812406,"url":"https://github.com/warrant-dev/react-warrant-js","last_synced_at":"2025-04-13T21:13:21.271Z","repository":{"id":46554365,"uuid":"380348383","full_name":"warrant-dev/react-warrant-js","owner":"warrant-dev","description":"React Client SDK for Warrant","archived":false,"fork":false,"pushed_at":"2024-06-18T04:21:58.000Z","size":335,"stargazers_count":16,"open_issues_count":5,"forks_count":1,"subscribers_count":2,"default_branch":"master","last_synced_at":"2025-04-13T21:13:15.660Z","etag":null,"topics":["abac","access-control","acl","attribute-based-access-control","authorization","authz","javascript","permissions","rbac","react","role-based-access-control"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/warrant-dev.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2021-06-25T20:34:40.000Z","updated_at":"2025-04-09T10:18:51.000Z","dependencies_parsed_at":"2024-11-07T23:43:45.176Z","dependency_job_id":null,"html_url":"https://github.com/warrant-dev/react-warrant-js","commit_stats":null,"previous_names":[],"tags_count":11,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/warrant-dev%2Freact-warrant-js","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/warrant-dev%2Freact-warrant-js/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/warrant-dev%2Freact-warrant-js/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/warrant-dev%2Freact-warrant-js/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/warrant-dev","download_url":"https://codeload.github.com/warrant-dev/react-warrant-js/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248782260,"owners_count":21160717,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["abac","access-control","acl","attribute-based-access-control","authorization","authz","javascript","permissions","rbac","react","role-based-access-control"],"created_at":"2024-11-07T23:32:42.294Z","updated_at":"2025-04-13T21:13:21.206Z","avatar_url":"https://github.com/warrant-dev.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# @warrantdev/react-warrant-js\n\n[![npm](https://img.shields.io/npm/v/@warrantdev/react-warrant-js)](https://www.npmjs.com/package/@warrantdev/react-warrant-js)\n\n## Overview\n\nThe Warrant React library provides components, hooks, and helper methods for controlling access to pages and components in React using [Warrant](https://warrant.dev/). The library interacts directly with the Warrant API using short-lived session tokens that must be created server-side using your API key. Refer to [this guide](https://docs.warrant.dev/guides/creating-session-tokens) to see how to generate session tokens for your users.\n\n## Installation\n\nUse `npm` to install the core Warrant client module [`@warrantdev/warrant-js`](https://github.com/warrant-dev/warrant-js). This module includes methods shared across our client libraries (Vue, Angular, etc.) and additional types (for TypeScript users).\n\n```sh\nnpm install @warrantdev/warrant-js\n```\n\nUse `npm` to install `@warrantdev/react-warrant-js`:\n\n```sh\nnpm install @warrantdev/react-warrant-js\n```\n\n## Usage\n\n### `WarrantProvider`\n\nWrap your application with `WarrantProvider`, passing it your Client Key using the `clientKey` prop. `WarrantProvider` uses [React Context](https://reactjs.org/docs/context.html) to allow you to access utility methods for performing access checks anywhere in your app.\n\n```jsx\n// App.jsx\nimport React from \"react\";\nimport { WarrantProvider } from \"@warrantdev/react-warrant-js\";\n\nconst App = () =\u003e {\n  return (\n    \u003cWarrantProvider clientKey=\"client_test_f5dsKVeYnVSLHGje44zAygqgqXiLJBICbFzCiAg1E=\"\u003e\n      {/* Routes, ThemeProviders, etc. */}\n    \u003c/WarrantProvider\u003e\n  );\n};\n\nexport default App;\n```\n\n#### **Setting the Session Token**\n\nIn order to finish initializing the library and begin performing access checks in your app, you must provide a server-generated session token and set it using the `setSessionToken` method. Otherwise your requests will be denied by the Warrant API.\n\nSet the session token using the `useWarrant` hook:\n\n```jsx\n// Login.jsx\nimport React from \"react\";\nimport { useWarrant } from \"@warrantdev/react-warrant-js\";\n\nconst Login = () =\u003e {\n  const { setSessionToken } = useWarrant();\n\n  const loginUser = async (event) =\u003e {\n    const response = await login(email, password);\n\n    // NOTE: This session token must be generated\n    // server-side when logging users into your\n    // application and then passed to the client.\n    // Access check calls in this library will fail\n    // if the session token is invalid or not set.\n    setSessionToken(response.warrantSessionToken);\n\n    //\n    // Redirect user to logged in page\n    //\n  };\n\n  return (\n    \u003cform onSubmit={loginUser}\u003e{/* email \u0026 password inputs, etc. */}\u003c/form\u003e\n  );\n};\n\nexport default Login;\n```\n\nOr using `Context.Consumer`:\n\n```jsx\nimport React from \"react\";\nimport { WarrantContext } from \"@warrantdev/react-warrant-js\";\n\nconst Login = () =\u003e {\n  const loginUser = (setSessionToken) =\u003e {\n    return async (event) =\u003e {\n      const response = await login(email, password);\n\n      // NOTE: This session token must be generated\n      // server-side when logging users into your\n      // application and then passed to the client.\n      // Access check calls in this library will fail\n      // if the session token is invalid or not set.\n      setSessionToken(response.warrantSessionToken);\n\n      //\n      // Redirect user to logged in page\n      //\n    };\n  };\n\n  return (\n    \u003cWarrantContext.Consumer\u003e\n      {({ setSessionToken }) =\u003e (\n        \u003cform onSubmit={loginUser(setSessionToken)}\u003e\n          {/* email \u0026 password inputs, etc. */}\n        \u003c/form\u003e\n      )}\n    \u003c/WarrantContext.Consumer\u003e\n  );\n};\n\nexport default Login;\n```\n\n### `check`\n\n`check` is a utility function that returns a `Promise` which resolves with `true` if the user for the current session token has the specified `relation` on the specified `object` and returns `false` otherwise. Use it for fine-grained conditional rendering or for specific logic within components.\n\nUsing `check` through the `useWarrant` hook:\n\n```jsx\nimport React, { useEffect } from \"react\";\nimport { useWarrant } from \"@warrantdev/react-warrant-js\";\n\nconst MyComponent = () =\u003e {\n  const { check } = useWarrant();\n\n  useEffect(() =\u003e {\n    const fetchProtectedInfo = async () =\u003e {\n      // Only fetch protected info from server if\n      // user can \"view\" the info object \"protected_info\".\n      const userIsAuthorized = await check({\n        object: {\n          objectType: \"info\",\n          objectId: \"protected_info\",\n        },\n        relation: \"viewer\",\n      });\n      if (userIsAuthorized) {\n        // request protected info from server\n      }\n    };\n\n    fetchProtectedInfo();\n  });\n\n  return (\n    \u003cdiv\u003e{protectedInfo \u0026\u0026 \u003cProtectedInfo\u003e{protectedInfo}\u003c/ProtectedInfo\u003e}\u003c/div\u003e\n  );\n};\n\nexport default MyComponent;\n```\n\nOr using the React Context API:\n\n```jsx\nimport React, { useEffect } from \"react\";\nimport { WarrantContext } from \"@warrantdev/react-warrant-js\";\n\nclass MyComponent extends React.Component {\n  async componentDidMount() {\n    const { check } = this.context;\n\n    // Only fetch protected info from server if\n    // user can \"view\" the info object \"protected_info\".\n    const userIsAuthorized = await check({\n      object: {\n        objectType: \"info\",\n        objectId: \"protected_info\",\n      },\n      relation: \"viewer\",\n    });\n    if (userIsAuthorized) {\n      await fetchProtectedInfo();\n    }\n  }\n\n  async fetchProtectedInfo() {\n    // request protected info from server\n  }\n\n  render() {\n    return (\n      \u003cdiv\u003e\n        {protectedInfo \u0026\u0026 \u003cProtectedInfo\u003e{protectedInfo}\u003c/ProtectedInfo\u003e}\n      \u003c/div\u003e\n    );\n  }\n}\n\nMyComponent.contextType = WarrantContext;\n\nexport default MyComponent;\n```\n\n### `checkMany`\n\n`checkMany` is a utility function that returns a `Promise` which resolves with `true` if the user for the current session token has _all of_ or _any of_ (based on a specified `op`) a set of specified `warrants` and returns `false` otherwise.\n\n```jsx\nimport { CheckOp } from \"@warrantdev/warrant-js\";\n\nconst { checkMany } = useWarrant();\n\n// userIsAuthorized will only be true if the user is\n// a member of tenant-A AND has permission view-protected-info\nconst userIsAuthorized = await checkMany({\n  op: CheckOp.AllOf,\n  warrants: [\n    {\n      object: {\n        objectType: \"tenant\",\n        objectId: \"tenant-A\",\n      },\n      relation: \"member\",\n    },\n    {\n      object: {\n        objectType: \"permission\",\n        objectId: \"view-protected-info\",\n      },\n      relation: \"member\",\n    },\n  ],\n});\n```\n\n### `hasPermission`\n\n`hasPermission` is a utility function that returns a `Promise` which resolves with `true` if the user for the current session token has the specified `permissionId` and returns `false` otherwise.\n\n```jsx\nimport { CheckOp } from \"@warrantdev/warrant-js\";\n\nconst { hasPermission } = useWarrant();\n\n// userHasPermission will only be true if the user\n// has the permission view-protected-info\nconst userHasPermission = await hasPermission({\n  permissionId: \"view-protected-info\",\n});\n```\n\n### `hasFeature`\n\n`hasFeature` is a utility function that returns a `Promise` which resolves with `true` if the user for the current session token has the specified `featureId` and returns `false` otherwise.\n\n```jsx\nimport { CheckOp } from \"@warrantdev/warrant-js\";\n\nconst { hasFeature } = useWarrant();\n\n// userHasFeature will only be true if the user\n// has the feature protected-info\nconst userHasFeature = await hasFeature({\n  featureId: \"protected-info\",\n});\n```\n\n### `ProtectedComponent`\n\n`ProtectedComponent` is a utility component you can wrap around markup or components that should only be accessible to users with certain privileges. It only renders the components it wraps if the user has the given warrants.\n\n```jsx\nimport React from \"react\";\nimport { ProtectedComponent } from \"@warrantdev/react-warrant-js\";\n\nconst MyComponent = () =\u003e {\n  return (\n    \u003cdiv\u003e\n      \u003cMyPublicComponent /\u003e\n      {/* hides MyProtectedComponent unless the user can \"view\" myObject with id object.id */}\n      \u003cProtectedComponent\n        warrants={[\n          {\n            object: {\n              objectType: \"myObject\",\n              objectId: object.id,\n            },\n            relation: \"view\",\n          },\n        ]}\n      \u003e\n        \u003cMyProtectedComponent /\u003e\n      \u003c/ProtectedComponent\u003e\n    \u003c/div\u003e\n  );\n};\n\nexport default MyComponent;\n```\n\n### `PermissionProtectedComponent`\n\n`PermissionProtectedComponent` is a utility component you can wrap around markup or components that should only be accessible to users with certain privileges. It only renders the components it wraps if the user has the given permission.\n\n```jsx\nimport React from \"react\";\nimport { PermissionProtectedComponent } from \"@warrantdev/react-warrant-js\";\n\nconst MyComponent = () =\u003e {\n  return (\n    \u003cdiv\u003e\n      \u003cMyPublicComponent /\u003e\n      {/* hides MyProtectedComponent unless the user has permission \"view-protected-info\" */}\n      \u003cPermissionProtectedComponent permissionId=\"view-protected-info\"\u003e\n        \u003cMyProtectedComponent /\u003e\n      \u003c/PermissionProtectedComponent\u003e\n    \u003c/div\u003e\n  );\n};\n\nexport default MyComponent;\n```\n\n### `FeatureProtectedComponent`\n\n`FeatureProtectedComponent` is a utility component you can wrap around markup or components that should only be accessible to users with certain privileges. It only renders the components it wraps if the user has the given feature.\n\n```jsx\nimport React from \"react\";\nimport { FeatureProtectedComponent } from \"@warrantdev/react-warrant-js\";\n\nconst MyComponent = () =\u003e {\n  return (\n    \u003cdiv\u003e\n      \u003cMyPublicComponent /\u003e\n      {/* hides MyProtectedComponent unless the user has feature \"protected-info\" */}\n      \u003cFeatureProtectedComponent featureId=\"protected-info\"\u003e\n        \u003cMyProtectedComponent /\u003e\n      \u003c/FeatureProtectedComponent\u003e\n    \u003c/div\u003e\n  );\n};\n\nexport default MyComponent;\n```\n\n### `withWarrantCheck`\n\nUse the `withWarrantCheck` Higher Order Component (HOC) to protect components that should only be accessible to users with certain privileges.\n\n#### **Protecting Routes**\n\nNOTE: This example uses `react-router` but you can use any routing library.\n\n```jsx\n// App.jsx\nimport React from \"react\";\nimport { Router, Route, Switch } from \"react-router-dom\";\nimport { createBrowserHistory } from \"history\";\nimport { WarrantProvider, withWarrantCheck } from \"@warrantdev/react-warrant-js\";\nimport PublicPage from \"./PublicPage\";\nimport ProtectedPage from \"./ProtectedPage\";\n\nconst history = createBrowserHistory();\n\nconst App = () =\u003e {\n    return \u003cWarrantProvider clientKey=\"client_test_f5dsKVeYnVSLHGje44zAygqgqXiLJBICbFzCiAg1E=\"\u003e\n        \u003cRouter history={history}\u003e\n            \u003cSwitch\u003e\n                \u003cRoute path=\"/public_route\" exact component={PublicPage}/\u003e\n                {/*\n                    Only render ProtectedPage if the user\n                    can \"view\" the route \"protected_route\".\n                */}\n                \u003cRoute path=\"/protected_route\" exact component={withWarrantCheck(ProtectedPage, {\n                    warrants: [{\n                        object: {\n                            objectType: \"route\",\n                            objectId: \"protected_route\",\n                        },\n                        relation: \"view\",\n                    }],\n                    redirectTo: \"/public_route\",\n                })}\u003e\n            \u003c/Switch\u003e\n        \u003c/Router\u003e\n    \u003c/WarrantProvider\u003e;\n};\n\nexport default App;\n```\n\n#### **Protecting Components**\n\n```jsx\nimport React from \"react\";\nimport { withWarrantCheck } from \"@warrantdev/react-warrant-js\";\n\nconst MySecretComponent = () =\u003e {\n  return \u003cdiv\u003eSuper secret text\u003c/div\u003e;\n};\n\n// Only render MySecretComponent if the user\n// can \"view\" the component \"MySecretComponent\".\nexport default withWarrantCheck(MySecretComponent, {\n  warrants: [\n    {\n      object: {\n        objectType: \"component\",\n        objectId: \"MySecretComponent\",\n      },\n      relation: \"view\",\n    },\n  ],\n  redirectTo: \"/\",\n});\n```\n\n### `withPermissionCheck`\n\nUse the `withPermissionCheck` Higher Order Component (HOC) to protect components that should only be accessible to users with a certain permission.\n\n#### **Protecting Routes**\n\nNOTE: This example uses `react-router` but you can use any routing library.\n\n```jsx\n// App.jsx\nimport React from \"react\";\nimport { Router, Route, Switch } from \"react-router-dom\";\nimport { createBrowserHistory } from \"history\";\nimport { WarrantProvider, withPermissionCheck } from \"@warrantdev/react-warrant-js\";\nimport PublicPage from \"./PublicPage\";\nimport ProtectedPage from \"./ProtectedPage\";\n\nconst history = createBrowserHistory();\n\nconst App = () =\u003e {\n    return \u003cWarrantProvider clientKey=\"client_test_f5dsKVeYnVSLHGje44zAygqgqXiLJBICbFzCiAg1E=\"\u003e\n        \u003cRouter history={history}\u003e\n            \u003cSwitch\u003e\n                \u003cRoute path=\"/public_route\" exact component={PublicPage}/\u003e\n                {/*\n                    Only render ProtectedPage if the user\n                    has the \"view-protected-route\" permission.\n                */}\n                \u003cRoute path=\"/protected_route\" exact component={withPermissionCheck(ProtectedPage, {\n                    permissionId: \"view-protected-route\",\n                    redirectTo: \"/public_route\",\n                })}\u003e\n            \u003c/Switch\u003e\n        \u003c/Router\u003e\n    \u003c/WarrantProvider\u003e;\n};\n\nexport default App;\n```\n\n#### **Protecting Components**\n\n```jsx\nimport React from \"react\";\nimport { withPermissionCheck } from \"@warrantdev/react-warrant-js\";\n\nconst MySecretComponent = () =\u003e {\n  return \u003cdiv\u003eSuper secret text\u003c/div\u003e;\n};\n\n// Only render MySecretComponent if the user\n// has the \"view-protected-route\" permission.\nexport default withPermissionCheck(MySecretComponent, {\n  permissionId: \"view-protected-route\",\n  redirectTo: \"/\",\n});\n```\n\n### `withFeatureCheck`\n\nUse the `withFeatureCheck` Higher Order Component (HOC) to protect components that should only be accessible to users with a certain feature.\n\n#### **Protecting Routes**\n\nNOTE: This example uses `react-router` but you can use any routing library.\n\n```jsx\n// App.jsx\nimport React from \"react\";\nimport { Router, Route, Switch } from \"react-router-dom\";\nimport { createBrowserHistory } from \"history\";\nimport { WarrantProvider, withFeatureCheck } from \"@warrantdev/react-warrant-js\";\nimport PublicPage from \"./PublicPage\";\nimport ProtectedPage from \"./ProtectedPage\";\n\nconst history = createBrowserHistory();\n\nconst App = () =\u003e {\n    return \u003cWarrantProvider clientKey=\"client_test_f5dsKVeYnVSLHGje44zAygqgqXiLJBICbFzCiAg1E=\"\u003e\n        \u003cRouter history={history}\u003e\n            \u003cSwitch\u003e\n                \u003cRoute path=\"/public_route\" exact component={PublicPage}/\u003e\n                {/*\n                    Only render ProtectedPage if the user\n                    has the \"protected-route\" feature.\n                */}\n                \u003cRoute path=\"/protected_route\" exact component={withFeatureCheck(ProtectedPage, {\n                    featureId: \"protected-route\",\n                    redirectTo: \"/public_route\",\n                })}\u003e\n            \u003c/Switch\u003e\n        \u003c/Router\u003e\n    \u003c/WarrantProvider\u003e;\n};\n\nexport default App;\n```\n\n#### **Protecting Components**\n\n```jsx\nimport React from \"react\";\nimport { withFeatureCheck } from \"@warrantdev/react-warrant-js\";\n\nconst MySecretComponent = () =\u003e {\n  return \u003cdiv\u003eSuper secret text\u003c/div\u003e;\n};\n\n// Only render MySecretComponent if the user\n// has the \"protected-route\" feature.\nexport default withFeatureCheck(MySecretComponent, {\n  featureId: \"protected-route\",\n  redirectTo: \"/\",\n});\n```\n\n## Notes\n\nWe’ve used a random Client Key in these code examples. Be sure to replace it with your\n[actual Client Key](https://app.warrant.dev) to\ntest this code through your own Warrant account.\n\nFor more information on how to use the Warrant API, please refer to the\n[Warrant API reference](https://docs.warrant.dev).\n\n## TypeScript support\n\nThis package includes TypeScript declarations for Warrant.\n\nNote that we may release new [minor and patch](https://semver.org/) versions of\n`@warrantdev/react-warrant-js` with small but backwards-incompatible fixes to the type\ndeclarations. These changes will not affect Warrant itself.\n\n## Warrant Documentation\n\n- [Warrant Docs](https://docs.warrant.dev/)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fwarrant-dev%2Freact-warrant-js","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fwarrant-dev%2Freact-warrant-js","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fwarrant-dev%2Freact-warrant-js/lists"}