Skip to main content

Using Warrant with React

The Warrant React SDK allows you to securely add authorization & access control checks directly in your React application to show/hide pages, components, and other content that requires privileged access. The SDK interacts directly with the Warrant API using short-lived session tokens that must be created server-side using your API key. Refer to our guide on Creating Sessions to learn how to generate session tokens you can pass to the Warrant React SDK to start performing client-side access checks.

The following guide assumes that you already have a Warrant account and corresponding API and Client keys. If you don't already have an account, you can sign up for one here.

note

The Warrant React SDK is intended for use in client-side applications to perform access checks that dictate the rendering of pages and components. Always ensure that server-side actions which modify state in your application (ex: an API call that writes to the database) are protected using one of Warrant's server-side SDKs. To learn how to add server-side access checks using Warrant, refer to this quickstart guide.

Create an Allowed Origin

Since the Warrant React SDK interacts directly with the Warrant API, you must first configure an Allowed Origin from the Warrant Dashboard to allow requests from your React application to the Warrant API. Requests from an origin not explicitly specified by an Allowed Origin will fail.

For example, if your React application is served at https://app.example.com, create an Allowed Origin for https://app.example.com to allow requests from that origin.

For local development, you can add an Allowed Origin for localhost. For example, if your local React application is being served on localhost port 3000, add an Allowed Origin for http://localhost:3000.

Allowed Origins support wildcards (*), so creating an Allowed Origin for https://*.example.com will allow requests coming from any subdomain of https://example.com such as https://foo.example.com and https://bar.example.com.

Install the SDK

Run the following command in your project directory to install the Warrant React SDK:

npm install @warrantdev/react-warrant-js

Add WarrantProvider

The Warrant React SDK uses React Context to allow you to access utility methods for performing access checks anywhere in your app. Wrap your application with WarrantProvider, passing it your Client Key using the clientKey prop.

App.jsx
import React from "react";
import { WarrantProvider } from "@warrantdev/react-warrant-js";

const App = () => {
return (
<WarrantProvider clientKey="client_test_f5dsKVeYnVSLHGje44zAygqgqXiLJBICbFzCiAg1E=">
{/* Routes, ThemeProviders, etc. */}
</WarrantProvider>
);
};

export default App;

Create and Set a Session Token

Warrant Sessions

To finish initializing the SDK for a given user, you must create a session token for the user and call the setSessionToken method with the created session token. This allows the SDK to make access check requests to the Warrant API on behalf of the user. Refer to our guide on Creating Sessions to learn how to generate session tokens for users. We recommend generating a session token for the user during your authentication flow. You can then return the token to the client and use it to initialize the SDK. Here's an example of what that might look like:

Login.jsx
import React from "react";
import { useWarrant } from "@warrantdev/react-warrant-js";

const Login = () => {
const { setSessionToken } = useWarrant();

const loginUser = async (event) => {
const response = await login(email, password);

// NOTE: This session token must be generated
// server-side when logging users into your
// application and then passed to the client.
// Access check calls in this library will fail
// if the session token is invalid or not set.
setSessionToken(response.warrantSessionToken);

//
// Redirect user to logged in page
//
};

return (
<form onSubmit={loginUser}>{/* email & password inputs, etc. */}</form>
);
};

export default Login;

Identity Provider Sessions

If you are using an identity provider (IdP) for your application's authentication, you can use tokens generated by the provider in place of a session token. To do so, make sure you have your JWKS endpoint configured correctly. Refer to Identity Provider Sessions to read more about configuring the use of third party tokens. Once configured, you can call setSessionToken with your IdP token in the authentication flow:

setSessionToken("eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWUsImlhdCI6MTUxNjIzOTAyMn0.NHVaYe26MbtOYhSKkoKYdFVomg4i8ZJd8_-RU8VNbftc4TSMb4bXP3l3YlNWACwyXPGffz5aXHc6lty1Y2t4SWRqGteragsVdZufDn5BlnJl9pdR_kdVFUsra2rWKEofkZeIC4yWytE58sMIihvo9H1ScmmVwBcQP6XETqYd0aSHp1gOa9RdUPDvoXQ5oqygTqVtxaDr6wUFKrKItgBMzWIdNZ6y7O9E0DhEPTbE9rfBo6KTFsHAZnMg4k68CDp2woYIaXbmYTWcvbzIuHO7_37GT79XdIwkm95QJ7hYC9RiwrV7mesbY4PAahERJawntho0my942XheVLmGwLMBkQ")

Add Access Checks to Your App

Sometimes pages or components should only be shown to users who have elevated levels of access. In other cases, a page or component should be accessible to all users, but not all of its functionality (e.g. hiding an 'Edit' button from read-only users or only fetching privileged data for admin users). For access-control-related conditional logic and conditional rendering of content, the Warrant React SDK provides:

  • check, checkMany, hasPermission, and hasFeature utility methods to add access checks within component logic.
  • ProtectedComponent, PermissionProtectedComponent, and FeatureProtectedComponent wrapper components to conditionally render elements on a page or in a component.
  • WithWarrantCheck, WithPermissionCheck, and WithFeatureCheck Higher Order Components (HOCs) to wrap components with for conditional rendering, useful for creating protected routes with your favorite router.

check and checkMany

Make specific access checks within a component using check and checkMany:

import React, { useEffect } from "react";
import { useWarrant } from "@warrantdev/react-warrant-js";

const MyComponent = () => {
const { check } = useWarrant();

useEffect(() => {
const fetchProtectedInfo = async () => {
// Only fetch protected info from server if
// user is a "viewer" of the info object "protected_info".
const userHasWarrant = await check({
object: {
objectType: "info",
objectId: "protected_info",
},
relation: "viewer",
});
if (userHasWarrant) {
// request protected info from server
}
};

fetchProtectedInfo();
});

return (
<div>{protectedInfo && <ProtectedInfo>{protectedInfo}</ProtectedInfo>}</div>
);
};

export default MyComponent;

ProtectedComponent

Wrap components and markup with ProtectedComponent to only render them if the user has the required warrant:

import React from "react";
import { ProtectedComponent } from "@warrantdev/react-warrant-js";

const MyComponent = () => {
return (
<div>
<MyPublicComponent />
{/* hides MyProtectedComponent unless the user is a "viewer" of myObject with id object.id */}
<ProtectedComponent
warrants={[
{
object: {
objectType: "myObject",
objectId: object.id,
},
relation: "viewer",
},
]}
>
<MyProtectedComponent />
</ProtectedComponent>
</div>
);
};

export default MyComponent;

PermissionProtectedComponent

Wrap components and markup with PermissionProtectedComponent to only render them if the user has the required permission:

Using PermissionProtectedComponent
import React from "react";
import { ProtectedComponent } from "@warrantdev/react-warrant-js";

const MyComponent = () => {
return (
<div>
<MyPublicComponent />
{/* hides MyProtectedComponent unless the user has permission 'view-protected-component' */}
<PermissionProtectedComponent permissionId="view-protected-component">
<MyProtectedComponent />
</ProtectedComponent>
</div>
);
};

export default MyComponent;

FeatureProtectedComponent

Wrap components and markup with FeatureProtectedComponent to only render them if the user has the required feature:

Using FeatureProtectedComponent
import React from "react";
import { ProtectedComponent } from "@warrantdev/react-warrant-js";

const MyComponent = () => {
return (
<div>
<MyPublicComponent />
{/* hides MyProtectedComponent unless the user has feature 'protected-component-feature' */}
<FeatureProtectedComponent featureId="protected-component-feature">
<MyProtectedComponent />
</ProtectedComponent>
</div>
);
};

export default MyComponent;

withWarrantCheck

Wrap components with the withWarrantCheck HOC to ensure that a check for the required warrant is always performed before the component is rendered in any context of your application. This can be useful for building protected routes that are only accessible to users with the required warrant(s).

Using withWarrantCheck
import React from "react";
import { withWarrantCheck } from "@warrantdev/react-warrant-js";

const MySecretComponent = () => {
return <div>Super secret text</div>;
};

// Only render MySecretComponent if the user
// can "view" the component "MySecretComponent".
export default withWarrantCheck(MySecretComponent, {
warrants: [
{
object: {
objectType: "component",
objectId: "MySecretComponent",
},
relation: "view",
},
],
redirectTo: "/",
});

withPermissionCheck

Wrap components with the withPermissionCheck HOC to ensure that a check for the required permission is always performed before the component is rendered in any context of your application. This can be useful for building protected routes that are only accessible to users with the required permission.

Using withPermissionCheck
import React from "react";
import { withPermissionCheck } from "@warrantdev/react-warrant-js";

const MySecretComponent = () => {
return <div>Super secret text</div>;
};

// Only render MySecretComponent if the user
// has permission "view-secret-component".
export default withPermissionCheck(MySecretComponent, {
permissionId: "view-secret-component",
redirectTo: "/",
});

withFeatureCheck

Wrap components with the withFeatureCheck HOC to ensure that a check for the required feature is always performed before the component is rendered in any context of your application. This can be useful for building protected routes that are only accessible to users with the required feature.

Using withFeatureCheck
import React from "react";
import { withFeatureCheck } from "@warrantdev/react-warrant-js";

const MySecretComponent = () => {
return <div>Super secret text</div>;
};

// Only render MySecretComponent if the user
// has feature "secret-component".
export default withFeatureCheck(MySecretComponent, {
featureId: "secret-component",
redirectTo: "/",
});