Last active
August 15, 2024 01:52
-
-
Save karlhorky/a6a15e756394d0eaf206513175b33000 to your computer and use it in GitHub Desktop.
Guard components with auth permissions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// From the comment from @SukkaW here: | |
// https://github.com/vercel/next.js/pull/60616#issuecomment-1902608289 | |
// Here is what I am doing currently, to authenticate and authorize | |
// RSC pages and components (like a button or a tooltip) | |
function GuardedComponent() { | |
const user = useUser(); | |
// guard() will throw a `NoPermissionError` when the user doesn't have the permission | |
guard(user, permissionList); | |
return <div>Guarded content</div>; | |
} | |
// We can implement the `HideWhenNoPermissionBoundary` component based on React Error Boundary | |
// When `HideWhenNoPermissionBoundary` receives `NoPermissionError`, it returns null | |
// When `HideWhenNoPermissionBoundary` receives the other errors, re-throw | |
<Suspense> | |
<HideWhenNoPermissionBoundary> | |
<GuardedComponent /> | |
</HideWhenNoPermissionBoundary> | |
</Suspense> | |
// We can also implement the `RedirectWhenNoPermissionBoundary` component, also based on React Error Boundary | |
// When `RedirectWhenNoPermissionBoundary` receives `NoPermissionError`, it calls `redirect()` | |
// When `RedirectWhenNoPermissionBoundary` receives the other errors, re-throw the error | |
<Suspense> | |
<RedirectWhenNoPermissionBoundary to="/login"> | |
<GuardedComponent /> | |
</RedirectWhenNoPermissionBoundary> | |
</Suspense> | |
<Suspense> | |
<RedirectWhenNoPermissionBoundary to="/403"> | |
<GuardedComponent /> | |
</RedirectWhenNoPermissionBoundary> | |
</Suspense> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment