React Integration
Using AuthRail utilities in React and Next.js applications.
While the AuthRail core engine is framework-agnostic, we provide a set of first-class React utilities to make declarative and imperative authorization simple and performant.
1. RailBoundary
The RailBoundary is the most common way to protect sections of your UI. It evaluates a rail and renders its children only if authorized.
import { RailBoundary } from "authrail";
import { adminRail } from "@/lib/auth";
function AdminPortal({ user }) {
return (
<RailBoundary
rail={adminRail}
context={{ user }}
fallback={<Spinner />}
denied={<AccessDenied />}
onRedirect={(to) => router.push(to)} >
<AdminSettingsForm />
</RailBoundary>
);
}When to use:
- Protecting entire page sections.
- Showing/hiding sidebar items or complex widgets.
- Handling automated redirects at the component level.
2. useRail Hook
For times when you need to make logic-based decisions within your component body, use the useRail hook.
import { useRail } from "authrail";
function DeletePostButton({ post, user }) {
const { decision, status } = useRail(editRail, { user, post });
if (status === "loading") return null;
// Only render the button if the user is allowed to edit this post
return (
<button disabled={decision.type !== "allow"}>
Delete Post
</button>
);
}Return Object Properties:
status: One of"idle","loading", or"done".decision: The resultingDecisionobject (allow,deny,redirect).context: The final enriched context after evaluation.
3. protect (HOC)
The protect higher-order component is ideal for protecting page-level components or wrapping exports.
import { protect } from "authrail";
const SettingsPage = ({ user }) => {
return <div>Sensitive Settings</div>;
};
export default protect(
settingsRail,
(props) => ({ user: props.user }), // Get context from props
(to) => router.push(to), // Handle redirects
<LoadingState /> // Optional fallback
)(SettingsPage);Best Practices
Context Synchronization
React utilities automatically re-evaluate the rail whenever the context object changes. Ensure your context values are stable (memoized if necessary) to prevent excessive evaluations.
Progressive Disclosure
Use a mix of RailBoundary for large sections and useRail for micro-interactions (like enabling/disabling a single button). This creates a "smooth" experience where the user only sees what they are allowed to use.
Redirect Handling
AuthRail emits redirect intent. It doesn't perform the navigation itself. Always provide an onRedirect callback that integrates with your specific router (Next.js, React Router, TanStack Router, etc.).