Routing & Layout

Protected Route

Knock Codes shaped for route-level guarding, with an optional custom unauthorized state.

routing

Best used for Route-level guarding in React Router or similar, especially with a custom denial screen.

Meant for a React Router element or any layout-level guard where "locked" sometimes means "show a different route entirely" rather than "prompt inline."

Loading preview…
Installation

Add this block to your project

CLI

npx shadcn@latest add http://localhost:3000/r/react/protected-route.json

Running this site somewhere other than localhost? Set NEXT_PUBLIC_SITE_URL and this command switches to that host automatically.

Also installs

  • Knock Codes Core
  • Knock Codes Types
  • useKnockCodes
  • cx (classname helper)
  • Gate Wrapper
  • PIN Input
  • Knock Codes

Files created (11)

  • components/knock-codes/core/hash.ts
  • components/knock-codes/core/verify.ts
  • components/knock-codes/core/session.ts
  • components/knock-codes/core/storage.ts
  • components/knock-codes/react/types.ts
  • components/knock-codes/react/useKnockCodes.ts
  • components/knock-codes/react/cx.ts
  • components/knock-codes/react/GateWrapper.tsx
  • components/knock-codes/react/PinInput.tsx
  • components/knock-codes/react/KnockCodes.tsx
  • components/knock-codes/react/ProtectedRoute.tsx

No CLI? Copy the files by hand

  1. Open the Code tab in the preview above.
  2. Create each path listed below in your project and paste its contents in.
  3. Do the same for anything listed under “Also installs”, if present.

Props

API reference

PropTypeDefaultDescription
expectedHashstringSHA-256 hex hash to verify against, for local mode.
verifyVerifyFnCustom async verification function, for server mode.
children *ReactNodeRendered once unlocked.
unauthorizedFallbackReactNodeRendered instead of the default access-code prompt while locked. Omit for Knock Codes's default behavior.
labelsKnockCodesLabelsOverrides for every user-facing string.
variant"page" | "inline""page"Outer positioning.
Notes

Accessibility

Identical to Knock Codes when unauthorizedFallback is unset. When it is set, make sure whatever you pass as the fallback is itself accessible — this block doesn't manage focus for you across a route transition.

Customization

Pass `unauthorizedFallback` to render something other than an inline access-code prompt while locked — pair it with your router's own navigation for a redirect-on-lock pattern, or pass an `<AccessDeniedScreen>` for a hard-denial route.

Compose with

Blocks that pair well with this one

These combine naturally with this block, whether as a shared shell, a shared session, or a common fallback.