Skip to content
View as Markdown

WithGuard ​

WithGuard is a component for conditionally rendering UI elements based on guard evaluation. It uses the same guard system as route-level guards, making permission logic reusable throughout your application.

Import ​

tsx
import { WithGuard, pass, hidden, type Guard } from "@tailor-platform/app-shell";

The runnable examples also import useMemo and useState from react, and Button, Checkbox, Select, Spinner, and Text from @tailor-platform/app-shell.

The previews use local role, subscription, and permission values captured by their guards. They reuse the surrounding AppShell provider without changing its contextData or performing real authentication. In an application, read those values from the guard's { context } argument, as shown under Creating Guards. Keep each guards array stable with useMemo until its inputs change.

Basic Usage ​

Choose Admin to reveal the protected content, then switch back to Viewer to remove it from the DOM. Without a fallback, a hidden guard renders nothing.

tsx
function BasicUsage() {
  const [role, setRole] = useState("Viewer");
  const guards = useMemo<Guard[]>(() => [() => (role === "Admin" ? pass() : hidden())], [role]);

  return (
    <div className="max-w-sm space-y-3">
      <Select
        aria-label="Demo role"
        items={["Viewer", "Admin"]}
        value={role}
        onValueChange={(value) => {
          if (value) setRole(value);
        }}
      />
      <Text.p>Current role: {role}</Text.p>
      <WithGuard guards={guards}>
        <Text.p role="status">Admin settings are available.</Text.p>
      </WithGuard>
    </div>
  );
}

Props ​

Generated from the type surface — first-party props only.

WithGuardProps ​

PropTypeDefaultDescription
childrenReactNode-Content to render when all guards pass.
fallback?ReactNodenull (renders nothing)Content to render when any guard returns hidden.
guardsGuard[]-Guards to evaluate. All guards must pass for children to render. Uses the same Guard type as route guards for full reusability.
loading?ReactNodenull (renders nothing)Content to render while guards are being evaluated (for async guards).

Exports ​

  • WithGuard — const
  • WithGuardProps — type

Guard Functions ​

WithGuard uses the same Guard type as route guards:

typescript
type Guard = (ctx: GuardContext) => GuardResult | Promise<GuardResult>;

type GuardResult =
  | { type: "pass" } // Allow rendering
  | { type: "hidden" }; // Hide content (render fallback)

Note: Unlike route guards, redirectTo() is not supported in WithGuard. Use hidden() with a fallback that handles navigation if needed.

Creating Guards ​

tsx
import { type Guard, pass, hidden } from "@tailor-platform/app-shell";

// Simple guard
const requireAuth: Guard = ({ context }) => {
  return context.currentUser ? pass() : hidden();
};

// Async guard with API call
const hasPermission: Guard = async ({ context }) => {
  const canAccess = await fetch("/api/permissions/admin")
    .then((r) => r.json())
    .then((data) => data.allowed);

  return canAccess ? pass() : hidden();
};

// Parameterized guard (curried function)
const isOwner =
  (resourceId: string): Guard =>
  ({ context }) => {
    return context.currentUser?.id === resourceId ? pass() : hidden();
  };

Examples ​

Simple Role Check ​

The Basic Usage example demonstrates role-based visibility without a fallback.

With Fallback ​

Show alternative content when a guard fails. Toggle Premium subscription to switch between the upgrade prompt and the protected analytics content.

tsx
function WithFallback() {
  const [premium, setPremium] = useState(false);
  const guards = useMemo<Guard[]>(() => [() => (premium ? pass() : hidden())], [premium]);

  return (
    <div className="space-y-3">
      <Checkbox label="Premium subscription" checked={premium} onCheckedChange={setPremium} />
      <WithGuard
        guards={guards}
        fallback={<Text.p role="status">Upgrade to view analytics.</Text.p>}
      >
        <Text.p role="status">Premium analytics are available.</Text.p>
      </WithGuard>
    </div>
  );
}

With Loading State ​

The local permission check waits briefly so its spinner and loading announcement can be observed without an API. Toggle Allow permission check to try both outcomes, or use Check permission again to repeat the current check. Each request gets a stable guards array; a new request reevaluates it without changing AppShell's context.

tsx
function WithLoadingState() {
  const [request, setRequest] = useState({ allowed: false });
  const guards = useMemo<Guard[]>(
    () => [
      async () => {
        await new Promise((resolve) => setTimeout(resolve, 700));
        return request.allowed ? pass() : hidden();
      },
    ],
    [request],
  );

  return (
    <div className="space-y-3">
      <Checkbox
        label="Allow permission check"
        checked={request.allowed}
        onCheckedChange={(allowed) => setRequest({ allowed })}
      />
      <Button variant="outline" onClick={() => setRequest((current) => ({ ...current }))}>
        Check permission again
      </Button>
      <WithGuard
        guards={guards}
        loading={
          <div role="status" className="flex items-center gap-2">
            <Spinner />
            <Text.span>Checking permission…</Text.span>
          </div>
        }
        fallback={<Text.p role="status">Permission denied.</Text.p>}
      >
        <Text.p role="status">Permission granted.</Text.p>
      </WithGuard>
    </div>
  );
}

Multiple Guards ​

All guards must pass for content to render. Enable Admin access and Beta feature enabled in either order; the protected feature appears only when both are enabled.

tsx
function MultipleGuards() {
  const [admin, setAdmin] = useState(false);
  const [betaEnabled, setBetaEnabled] = useState(false);
  const guards = useMemo<Guard[]>(
    () => [() => (admin ? pass() : hidden()), () => (betaEnabled ? pass() : hidden())],
    [admin, betaEnabled],
  );

  return (
    <div className="space-y-3">
      <Checkbox label="Admin access" checked={admin} onCheckedChange={setAdmin} />
      <Checkbox
        label="Beta feature enabled"
        checked={betaEnabled}
        onCheckedChange={setBetaEnabled}
      />
      <WithGuard
        guards={guards}
        fallback={
          <Text.p role="status">Both admin access and the beta feature are required.</Text.p>
        }
      >
        <Text.p role="status">Beta admin feature is available.</Text.p>
      </WithGuard>
    </div>
  );
}

Parameterized Guards ​

Use curried functions to create reusable parameterized guards. This preview signs in no one: alex is a local fixture for the current user. Change the record's owner to see the ownership check pass or fail. A real ownership guard reads the current user's ID from { context }.

tsx
function ParameterizedGuards() {
  const currentUserId = "alex";
  const [ownerId, setOwnerId] = useState("alex");
  const guards = useMemo<Guard[]>(() => {
    const isOwner =
      (resourceOwnerId: string): Guard =>
      () =>
        resourceOwnerId === currentUserId ? pass() : hidden();
    return [isOwner(ownerId)];
  }, [currentUserId, ownerId]);

  return (
    <div className="max-w-sm space-y-3">
      <Text.p>Signed in as: {currentUserId}</Text.p>
      <Select
        aria-label="Record owner"
        items={["alex", "sam"]}
        value={ownerId}
        onValueChange={(value) => {
          if (value) setOwnerId(value);
        }}
      />
      <WithGuard
        guards={guards}
        fallback={<Text.p role="status">Only the record owner can edit.</Text.p>}
      >
        <Text.p role="status">You can edit this record.</Text.p>
      </WithGuard>
    </div>
  );
}

In Sidebar Navigation ​

Conditionally show navigation items:

tsx
import { DefaultSidebar, SidebarItem, WithGuard } from "@tailor-platform/app-shell";

const isAdmin = ({ context }) => (context.currentUser?.role === "admin" ? pass() : hidden());

<DefaultSidebar>
  <SidebarItem to="/dashboard" />
  <SidebarItem to="/products" />

  <WithGuard guards={[isAdmin]}>
    <SidebarItem to="/admin" />
    <SidebarItem to="/settings" />
  </WithGuard>
</DefaultSidebar>;

Feature Flags ​

The Multiple Guards example combines a feature flag with a role check. For a guard reusable in both routes and WithGuard, read the flag from your application's typed context data:

tsx
const hasBetaFeature: Guard = ({ context }) =>
  context.featureFlags?.newDashboard ? pass() : hidden();

Subscription Tiers ​

The With Fallback example switches between a free-tier prompt and premium content. The equivalent reusable guard reads the subscription from your application's typed context data:

tsx
const isPremium: Guard = ({ context }) =>
  context.currentUser?.subscription === "premium" ? pass() : hidden();

The fallback can also be a card or an upgrade link owned by your application.

Dynamic Permissions ​

The With Loading State example demonstrates pending, allowed, and denied states with a local delayed check. Replace that check with your permission API in an application; the loading and fallback behavior is unchanged. See Creating Guards for an API-backed guard shape.

Combining with Route Guards ​

Reuse the same guards for routes and UI:

tsx
// guards.ts
export const requireAuth: Guard = ({ context }) => {
  return context.currentUser ? pass() : hidden();
};

export const isAdmin: Guard = ({ context }) => {
  return context.currentUser?.role === "admin" ? pass() : hidden();
};

// routes.tsx
const adminModule = defineModule({
  path: "admin",
  component: AdminPage,
  guards: [requireAuth, isAdmin], // Route-level
});

// component.tsx
<WithGuard guards={[requireAuth, isAdmin]}>
  {" "}
  {/* UI-level */}
  <AdminSettings />
</WithGuard>;

Guard Evaluation ​

Guards are evaluated in order and stop at the first non-pass result:

tsx
const guards = [guardA, guardB, guardC];

// If guardA returns hidden(), guardB and guardC are NOT evaluated
<WithGuard guards={guards}>
  <Content />
</WithGuard>;

Performance ​

Caching ​

WithGuard caches guard results while both the contextData reference and the guards array remain unchanged:

  • Guards re-evaluate when either contextData or the guards array reference changes.
  • Other prop changes do not re-evaluate guards.
  • Define fixed guards outside the component, or memoize a guards array with the values its functions capture. Creating a new array on an unrelated render starts another evaluation, including another asynchronous check.

Suspense Integration ​

Async guards use React Suspense:

  • Shows loading prop while evaluating
  • Renders children or fallback when complete
  • Automatically suspends during evaluation

Context Data ​

Guards receive the same context as route guards:

typescript
// Define context type
declare module "@tailor-platform/app-shell" {
  interface AppShellRegister {
    contextData: {
      currentUser: User | null;
      featureFlags: FeatureFlags;
      permissions: string[];
    };
  }
}

// Use in guards
const hasPermission =
  (perm: string): Guard =>
  ({ context }) => {
    return context.permissions.includes(perm) ? pass() : hidden();
  };

Comparison: WithGuard vs Route Guards ​

FeatureWithGuardRoute Guards
PurposeConditional UI renderingRoute access control
LocationInside componentsModule/resource definitions
Supports pass()✅ Yes✅ Yes
Supports hidden()✅ Yes✅ Yes
Supports redirectTo()❌ No✅ Yes
Async guards✅ Yes✅ Yes
Reusable✅ Yes✅ Yes

Best Practices ​

Do: ​

  • ✅ Reuse guards between routes and UI
  • ✅ Use descriptive guard names (isAdmin, canEdit)
  • ✅ Provide fallback for better UX
  • ✅ Show loading state for async guards
  • ✅ Cache expensive permission checks

Don't: ​

  • ❌ Use redirectTo() in WithGuard (not supported)
  • ❌ Make guards too complex (extract to functions)
  • ❌ Forget to handle loading states
  • ❌ Skip fallback when hiding important features
  • ❌ Duplicate permission logic (reuse guards)

Accessibility ​

  • Content is fully removed from DOM when hidden (not just visually)
  • Screen readers won't announce hidden content
  • Loading states should be announced to screen readers
  • Fallback content should be accessible

TypeScript ​

Full type safety with TypeScript:

typescript
import { type Guard, type WithGuardProps } from "@tailor-platform/app-shell";

// Type-safe guard
const isAdmin: Guard = ({ context }) => {
  // context is fully typed
  return context.currentUser?.role === "admin" ? pass() : hidden();
};

// Type-safe props
const guardProps: WithGuardProps = {
  guards: [isAdmin],
  children: <AdminPanel />,
  fallback: <AccessDenied />,
};

Troubleshooting ​

Guard not re-evaluating ​

Problem: Guard doesn't update when data changes

Solution: Ensure contextData reference changes:

tsx
// ❌ Bad - mutating object
context.currentUser.role = "admin";

// ✅ Good - new reference
setContextData({
  ...contextData,
  currentUser: { ...currentUser, role: "admin" },
});

Infinite loading ​

Problem: Loading state never resolves

Solution: Ensure async guards return a result:

tsx
// ❌ Bad - no return
const checkPermission: Guard = async ({ context }) => {
  await fetch("/api/check");
  // Missing return!
};

// ✅ Good - returns result
const checkPermission: Guard = async ({ context }) => {
  const allowed = await fetch("/api/check").then((r) => r.json());
  return allowed ? pass() : hidden();
};

API Reference ​