Skip to content

Instantly share code, notes, and snippets.

@karlhorky
Last active January 21, 2024 13:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save karlhorky/a6a15e756394d0eaf206513175b33000 to your computer and use it in GitHub Desktop.
Save karlhorky/a6a15e756394d0eaf206513175b33000 to your computer and use it in GitHub Desktop.
Guard components with auth permissions
// 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