The SDK provides two methods for getting an authorization verdict on a Resource-action pair (that is, whether the logged-in Member is authorized to perform the specified action on the specified Resource).
The isAuthorizedSync method will use locally-cached instances of the Member and the configured RBAC policy. If the RBAC policy has not been loaded, this method will always return false. The SWR caching strategy is detailed here.
To ensure the RBAC policy has been loaded, use the isAuthorized function. It will return a Promise that resolves after the RBAC policy has been loaded.
If the Member is not logged in, these methods will always return false. If the Resource or action provided are not valid for the configured RBAC policy, these methods will also return false.
As a best practice, authorization checks for sensitive actions should also occur on the backend.
In React, the @stytch/react library provides the useStytchIsAuthorized hook that implements these methods for you. It returns two boolean values.
- isAuthorized indicates whether the Member is authorized. It could be false even if the Member is actually authorized if the result is from the cache and the underlying data has changed.
- fromCache indicates whether the value was returned from the application cache. If true, a state refresh is in progress.
In Next.js, useStytchIsAuthorized also returns a third boolean value.
- isInitialized indicates whether the cache is initialized.