Quick Start
Get up and running with AuthRail in minutes.
Follow these steps to integrate AuthRail into your application.
Follow these steps to integrate AuthRail into your application in less than 5 minutes.
Install the package
Install the authrail core package using your preferred package manager.
npm install authrailDefine your Rail
A Rail is the blueprint for your authorization logic. It is a sequence of middleware checks that a request context must pass. Create a shared file (e.g., lib/auth.ts) so you can reuse these definitions across several environments.
import { createRail, requireAuth, requireRole } from "authrail";
// 1. Define the shape of your context for full type safety
type AppContext = {
user: { id: string; role: "admin" | "user" } | null;
path: string;
};
// 2. Create the rail with specific middleware
export const adminRail = createRail<AppContext>("admin", [
requireAuth("/login"), // If user is null, emit a redirect to /login
requireRole("admin"), // If role isn't 'admin', emit a 'deny' decision
]);Pro Tip: By exporting your rails from a shared file, you ensure that you always use the same source of truth for permissions across several environments.
Evaluate in your application
Now, use the rail to protect a resource. This could be a Next.js Server Component, an Express route, or a React component.
In this example, we'll use a Next.js Server Component:
import { adminRail } from "@/lib/auth";
import { getCurrentUser } from "@/lib/session";
import { redirect } from "next/navigation";
export default async function AdminPage() {
const user = await getCurrentUser();
// 1. Evaluate the rail with the current context
const result = await adminRail.evaluate({
user,
path: "/admin"
});
// 2. Handle the decision based on the result type
if (result.decision.type === "redirect") {
redirect(result.decision.to);
}
if (result.decision.type === "deny") {
return (
<div className="p-4 border border-red-500 bg-red-50">
<h1>Access Denied</h1>
<p>You do not have permission to view this page.</p>
</div>
);
}
// 3. Render content (Access Allowed)
return <h1>Welcome to the Admin Dashboard</h1>;
}What just happened?
When adminRail.evaluate was called:
- It checked if
userwas present. If not, it would have returned aredirectdecision. - It checked if
user.rolewas"admin". If not, it would have returned adenydecision. - Since both passed, it returned an
allowdecision, letting the component render.
Next Steps
Now that you've secured your first route, explore the full power of AuthRail:
- Middleware Deep Dive - Learn about
allowIf,blockIf, and custom logic. - React Integration - Use the
RailBoundaryanduseRailhook. - Advanced Patterns - Learn how to enrich context and compose complex rules.