agentleFS
PolarCoding85PolarCoding85/convex-agent-skillz/.claude/skills/convex-auth-skill/SKILL.md

convex-auth

Skill16 starsChanged 10 months agoMITView on GitHub

Core authentication patterns for Convex backends. Use when implementing auth checks in functions, storing users in database, creating auth helpers, or debugging auth issues. Works with any auth provider (Clerk, WorkOS, Auth0, etc.).

3 other projects use a version of this.

Adopted by

Most recently taken up by

  • Other versions3 projects use a version of this.

    Word for word · 0

    None found.

    Edited · 0

    None found.

    Wrote their own version · 3

    1. get-convex/agent-skills★ 63same name
    2. FabienGreard/TouchGrassBar★ 4same name
    3. getsentry/friday★ 0same name

    How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.

  • In this repository5 other files it gives its agents.

The file

Show its rules and text

We split this skill into the rules it gives an agent

14 rules. 0 are common, 1 is distinctive, and 13 are very specific to this project.

  • 0

    Common

    Most of the 3 edited versions we read keep these.

  • 1

    Distinctive

    This author's own choices. Worth a look.

  • 13

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    Client-side: Always use useConvexAuth() from convex/react, NOT your provider's hook:

    line 46
  2. Very specific:

    Create authenticated function wrappers using convex-helpers:

    line 87
  3. Very specific:

    Check if query runs before auth completes (use "skip" pattern)

    line 183
  4. Very specific:

    Check auth.config.ts is deployed (npx convex dev)

    line 184
  5. Distinctive:

    Check Settings > Authentication in Convex Dashboard

    line 185
  6. Very specific:

    Verify JWT token at https://jwt.io - check iss and aud fields

    line 186
  7. Very specific:

    Ensure domain in auth.config.ts matches JWT iss

    line 187
  8. Very specific:

    Ensure applicationID matches JWT aud

    line 188
  9. Very specific:

    Always check ctx.auth.getUserIdentity() in public functions

    line 192
  10. Very specific:

    Use useConvexAuth() hook, not provider's auth hook

    line 193
  11. Very specific:

    Use <Authenticated> component to gate protected content

    line 195
  12. Very specific:

    Use tokenIdentifier or subject as unique user key

    line 197
  13. Very specific:

    Run queries before checking isAuthenticated

    line 202
  14. Very specific:

    Use .filter() to find users by token (use index)

    line 203

“Common” is measured: kept by at least 6 in 10 of the 3 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Convex Authentication - Core Patterns

This skill covers universal auth patterns that work with ANY authentication provider.

Auth in Functions

Access the authenticated user via ctx.auth.getUserIdentity():

import { query, mutation, action } from './_generated/server';

export const myQuery = query({
  args: {},
  handler: async (ctx) => {
    const identity = await ctx.auth.getUserIdentity();
    if (identity === null) {
      throw new Error('Not authenticated');
    }
    // identity.tokenIdentifier - unique across providers
    // identity.subject - user ID from provider
    // identity.email, identity.name, etc. (if configured)
  }
});

UserIdentity Fields

FieldGuaranteedDescription
tokenIdentifier✅Unique ID (subject + issuer combined)
subject✅User ID from auth provider
issuer✅Auth provider domain
emailProvider-dependentUser's email
nameProvider-dependentDisplay name
pictureUrlProvider-dependentAvatar URL

Critical: Race Condition Prevention

Problem: Queries can execute before auth is validated on page load.

Client-side: Always use useConvexAuth() from convex/react, NOT your provider's hook:

// ✅ Correct - waits for Convex to validate token
import { useConvexAuth } from 'convex/react';
const { isLoading, isAuthenticated } = useConvexAuth();

// ❌ Wrong - only checks provider, not Convex validation
const { isSignedIn } = useAuth(); // from @clerk/clerk-react

Skip queries until authenticated:

const user = useQuery(api.users.current, isAuthenticated ? {} : 'skip');

Use Convex auth components:

import { Authenticated, Unauthenticated, AuthLoading } from "convex/react";

<Authenticated>
  <Content /> {/* Queries here are safe */}
</Authenticated>
<Unauthenticated>
  <SignInButton />
</Unauthenticated>

Storing Users in Database

See USERS.md for complete patterns including:

  • Schema design with indexes
  • Storing users via client mutation
  • Storing users via webhooks (recommended for production)
  • Helper functions for user lookup

Custom Auth Wrappers

Create authenticated function wrappers using convex-helpers:

// convex/lib/auth.ts
import {
  query,
  mutation,
  action,
  QueryCtx,
  MutationCtx,
  ActionCtx
} from './_generated/server';
import {
  customQuery,
  customMutation,
  customAction,
  customCtx
} from 'convex-helpers/server/customFunctions';
import { ConvexError } from 'convex/values';

async function requireAuth(ctx: QueryCtx | MutationCtx | ActionCtx) {
  const identity = await ctx.auth.getUserIdentity();
  if (!identity) {
    throw new ConvexError('Not authenticated');
  }
  return identity;
}

export const authQuery = customQuery(
  query,
  customCtx(async (ctx) => {
    const identity = await requireAuth(ctx);
    return { identity };
  })
);

export const authMutation = customMutation(
  mutation,
  customCtx(async (ctx) => {
    const identity = await requireAuth(ctx);
    return { identity };
  })
);

export const authAction = customAction(
  action,
  customCtx(async (ctx) => {
    const identity = await requireAuth(ctx);
    return { identity };
  })
);

Usage:

import { authQuery } from './lib/auth';

export const myProtectedQuery = authQuery({
  args: {},
  handler: async (ctx) => {
    // ctx.identity is guaranteed to exist
    const userId = ctx.identity.subject;
  }
});

HTTP Actions with Auth

Pass JWT in Authorization header:

// Client
fetch('https://your-deployment.convex.site/api/endpoint', {
  headers: { Authorization: `Bearer ${jwtToken}` }
});

// convex/http.ts
import { httpAction } from './_generated/server';

export const myEndpoint = httpAction(async (ctx, request) => {
  const identity = await ctx.auth.getUserIdentity();
  if (!identity) {
    return new Response('Unauthorized', { status: 401 });
  }
  // ...
});

Debugging Checklist

See DEBUG.md for detailed troubleshooting steps.

Quick checks:

  1. ctx.auth.getUserIdentity() returns null?
    • Check if query runs before auth completes (use "skip" pattern)
    • Check auth.config.ts is deployed (npx convex dev)
  2. Check Settings > Authentication in Convex Dashboard
  3. Verify JWT token at https://jwt.io - check iss and aud fields
  4. Ensure domain in auth.config.ts matches JWT iss
  5. Ensure applicationID matches JWT aud

DO ✅

  • Always check ctx.auth.getUserIdentity() in public functions
  • Use useConvexAuth() hook, not provider's auth hook
  • Skip queries with "skip" until authenticated
  • Use <Authenticated> component to gate protected content
  • Store users in DB for cross-user queries
  • Use tokenIdentifier or subject as unique user key

DON'T ❌

  • Trust client-side auth alone (Convex is a public API)
  • Run queries before checking isAuthenticated
  • Use .filter() to find users by token (use index)
  • Assume identity fields exist (check provider config)
  • Forget to redeploy after changing auth.config.ts

Download now (ZIP)

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
What did you use it for? e.g. Reviewing pull requests in a Rails app

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.