frontend-auth-clerk
Skill1 starsChanged 10 months agoMITView on GitHub
Clerk auth in a React (Vite) webapp — the token/interceptor contract, sign-in/sign-up flows, route guards, admin-only UI, org-switch state resets, and styling Clerk components with design tokens. Use when asked to "add sign-in", "guard a route", "hide something for non-admins", "check the current user in the frontend", or anything touching Clerk components, sessions, or tenant switching in the webapp.
- Reads credentials
In this repository14 other files it gives its agents.
- AGENTS.mdAGENTS.md
- skill-creatorSkill
- backend-ai-agentSkill
- backend-ai-toolsSkill
- backend-auth-clerkSkill
- backend-compressionSkill
- backend-metricsSkill
- backend-model-creationSkill
- backend-route-creationSkill
- backend-scaffoldingSkill
- backend-websocketSkill
- frontend-hooks-creationSkill
- frontend-scaffoldingSkill
- new-project-scaffoldingSkill
The file
We split this skill into the rules it gives an agent
3 rules. About 0 are common, 0 are distinctive, and 3 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈0
Distinctive · estimate
This author's own choices. Worth a look.
3
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 58
Never trigger API calls from components rendered outside AuthSetup.
- Very specific: line 141
When adding client-side caches, contexts, or localStorage entries holding tenant data: either key them by org id or wire them into …
- Very specific: line 145
Put UserButton and OrganizationSwitcher hidePersonal in the app's nav (typically the sidebar footer).
≈ “Common” is an estimate: at least 1 in 5 of the 350,495 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Clerk Auth (Webapp)
Clerk auth for the standard React + Vite + React Router + React Query + axios webapp. The backend half — middleware, org scoping, token verification — is in the backend-auth-clerk skill.
Package: @clerk/clerk-react.
The token contract (don't break this)
An AuthSetup component in main.tsx does two things, once, inside ClerkProvider:
// Installs Clerk's getToken into the shared axios instance, and blocks
// rendering until Clerk's session is loaded so React Query hooks can't fire
// requests before getToken() is reliable (avoids a startup-401 race).
function AuthSetup({ children }: { children: React.ReactNode }) {
const { getToken, isLoaded } = useAuth();
const installed = useRef(false);
useEffect(() => {
if (!installed.current) {
setupAuthInterceptor(getToken);
installed.current = true;
}
}, [getToken]);
if (!isLoaded) return null;
return <>{children}</>;
}And in the shared axios module (src/api/client.ts):
export function setupAuthInterceptor(getToken: () => Promise<string | null>) {
apiClient.interceptors.request.use(async (config) => {
const token = await getToken(); // fresh per request; Clerk caches/refreshes internally
if (token) config.headers.Authorization = `Bearer ${token}`;
return config;
});
}Provider order in main.tsx (Clerk must sit above the router):
ClerkProvider (publishableKey, signInUrl="/sign-in", signUpUrl="/sign-up", afterSignOutUrl="/sign-in")
> QueryClientProvider > AuthSetup > BrowserRouter > AppConsequences:
- API modules and React Query hooks need ZERO token plumbing. Never thread tokens through hooks or components.
- Never trigger API calls from components rendered outside
AuthSetup. - The axios instance stays importable from plain non-React modules — keep the interceptor-injection pattern rather than converting to a hook-based fetch wrapper.
Sign-in/sign-up routes and guards
<Routes>
<Route path="/sign-in/*" element={<SignIn />} /> {/* Clerk <SignIn routing="path"> page */}
<Route path="/sign-up/*" element={<SignUp />} />
<Route element={<RequireAuth />}>
<Route element={<AppLayout />}>{/* ...all app pages... */}</Route>
</Route>
<Route path="*" element={<Navigate to="/" replace />} />
</Routes>- Sign-in/up pages render OUTSIDE the guard and layout, and MUST stay above any catch-all route or it swallows them.
<SignIn>honors aredirect_urlquery param viaforceRedirectUrl; each page also redirects away if already signed in. RequireAuthwraps the entire app as a layout route — new pages are automatically protected, no per-page work:
export function RequireAuth() {
const { isLoaded, isSignedIn } = useAuth();
const location = useLocation();
if (!isLoaded) return null; // no redirect flash
if (!isSignedIn) {
const from = `${location.pathname}${location.search}${location.hash}`;
return <Navigate to={`/sign-in?${new URLSearchParams({ redirect_url: from })}`} replace />;
}
return <Outlet />;
}Admin-only UI
Mirror the backend's admin gate (Clerk publicMetadata.role === 'admin') with a shared helper, used both to hide nav links and to guard routes:
export function isAdminUser(user: ReturnType<typeof useUser>['user']) {
return user?.publicMetadata?.role === 'admin';
}
export function RequireAdmin() {
const { user, isLoaded } = useUser();
if (!isLoaded) return null;
if (!isAdminUser(user)) return <Navigate to="/" replace />;
return <Outlet />;
}Client-side checks are UX only. The API's 401/403 is the enforcement; never treat hiding a button as security.
Tenancy: org switches must reset state
Clerk Organizations is the tenant. If query keys and client-side state are not org-scoped, switching orgs leaks the previous tenant's data. Two mechanisms, both mounted in the app layout:
// Records the first observed org without firing, so sign-in doesn't bounce.
export function useOrgSwitchReset() {
const { organization, isLoaded } = useOrganization();
const navigate = useNavigate();
const initialized = useRef(false);
const lastOrgId = useRef<string | undefined>(undefined);
useEffect(() => {
if (!isLoaded) return;
const orgId = organization?.id;
if (!initialized.current) {
initialized.current = true;
lastOrgId.current = orgId;
return;
}
if (orgId !== lastOrgId.current) {
lastOrgId.current = orgId;
// ...remove tenant-scoped localStorage keys here...
queryClient.clear();
navigate('/', { replace: true });
}
}, [isLoaded, organization?.id, navigate]);
}- Key tenant-scoped context providers by org id (
<SomeProvider key={organization?.id ?? 'no-org'}>) so a switch remounts them cleanly. - When adding client-side caches, contexts, or localStorage entries holding tenant data: either key them by org id or wire them into
useOrgSwitchReset. Otherwise they WILL bleed across tenants.
Clerk components and styling
- Put
UserButtonandOrganizationSwitcher hidePersonalin the app's nav (typically the sidebar footer). - Theme all Clerk components globally via
appearanceonClerkProvider. If the repo has a design-token system (see itsthemeskill, if present), read token values off:rootat runtime — Tailwind v4@themeemits every token as a CSS variable — instead of hardcoding colors:
function token(name: string): string {
return getComputedStyle(document.documentElement).getPropertyValue(name).trim();
}
export function clerkAppearance() {
const colorPrimary = token('--color-accent');
if (!colorPrimary) return {}; // stylesheet not ready — fall back to Clerk defaults
return {
variables: {
colorPrimary,
colorText: token('--color-ink'),
colorBackground: token('--color-surface'),
borderRadius: token('--radius-control'),
fontFamily: token('--font-sans'),
// ...remaining input/danger tokens as the palette provides
},
};
}- For per-component layout fixes, pass Tailwind utility classes through
appearance.elements— Clerk appends them to its internals. Example: constrain the org switcher inside a fixed-width sidebar withrootBox: 'min-w-0 flex-1',organizationSwitcherTrigger: 'w-full min-w-0 justify-start', andorganizationPreviewMainIdentifier: 'truncate'so long org names ellipsize instead of overflowing.
Environment
VITE_CLERK_PUBLISHABLE_KEY — read via import.meta.env in main.tsx; throw at boot if missing. Vite only exposes VITE_-prefixed vars to the client — a Clerk key under any other prefix (e.g. NEXT_PUBLIC_) is silently invisible. Restart the dev server after changing it; Vite bakes env at startup.
Reading the current user
useUser()→ profile (name, avatar,publicMetadata). Display identity comes from Clerk live; there is no local User model and no/api/users/me— don't build one without reading thebackend-auth-clerkskill first.useAuth()→isSignedIn,getToken,signOut.useOrganization()→ active org (id, name). Gate org-dependent UI on it; users without an active org get API 403s until they pick one in the switcher.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

