workos-convex-auth

Set up and configure WorkOS AuthKit authentication with Convex backend. Use when integrating AuthKit, configuring JWT providers, setting up environment variables, or implementing sign in and sign out flows with React and Vite. Supports Netlify deployment.

6 stars

Best use case

workos-convex-auth is best used when you need a repeatable AI agent workflow instead of a one-off prompt.

Set up and configure WorkOS AuthKit authentication with Convex backend. Use when integrating AuthKit, configuring JWT providers, setting up environment variables, or implementing sign in and sign out flows with React and Vite. Supports Netlify deployment.

Teams using workos-convex-auth should expect a more consistent output, faster repeated execution, less prompt rewriting.

When to use this skill

  • You want a reusable workflow that can be run more than once with consistent structure.

When not to use this skill

  • You only need a quick one-off answer and do not need a reusable workflow.
  • You cannot install or maintain the underlying files, dependencies, or repository context.

Installation

Claude Code / Cursor / Codex

$curl -o ~/.claude/skills/workos-convex-auth/SKILL.md --create-dirs "https://raw.githubusercontent.com/get-convex/components-submissions-directory/main/.cursor/skills/workos-convex-auth/SKILL.md"

Manual Installation

  1. Download SKILL.md from GitHub
  2. Place it in .claude/skills/workos-convex-auth/SKILL.md inside your project
  3. Restart your AI agent — it will auto-discover the skill

How workos-convex-auth Compares

Feature / Agentworkos-convex-authStandard Approach
Platform SupportNot specifiedLimited / Varies
Context Awareness High Baseline
Installation ComplexityUnknownN/A

Frequently Asked Questions

What does this skill do?

Set up and configure WorkOS AuthKit authentication with Convex backend. Use when integrating AuthKit, configuring JWT providers, setting up environment variables, or implementing sign in and sign out flows with React and Vite. Supports Netlify deployment.

Where can I find the source code?

You can find the source code on GitHub using the link provided at the top of the page.

SKILL.md Source

# WorkOS Convex Auth Skill

> **Always check official docs for the latest information:**
> - Convex + WorkOS: https://docs.convex.dev/auth/authkit/
> - WorkOS AuthKit: https://workos.com/docs/authkit
> - AuthKit React SDK: https://workos.com/docs/sdks/authkit-react
> - Auto provisioning: https://docs.convex.dev/auth/authkit/auto-provision
> - Netlify Docs: https://docs.netlify.com/

## When to use this skill

Use this skill when you need to:

- Set up WorkOS AuthKit with a Convex backend
- Configure dual JWT providers for SSO and User Management
- Set environment variables for localhost and production
- Implement sign in, sign out, and callback flows
- Access user identity in Convex functions
- Configure admin access checks based on email domain

## Architecture overview

The authentication flow works as follows:

1. User clicks Sign In on the frontend
2. WorkOS AuthKit redirects to hosted login page
3. User authenticates (Google, GitHub, email, etc.)
4. WorkOS redirects back to `/callback` with auth code
5. AuthKit exchanges code for session tokens
6. Convex validates JWT tokens against WorkOS JWKS endpoint
7. `ctx.auth.getUserIdentity()` returns user claims from JWT

## Required packages

```bash
npm install @workos-inc/authkit-react @convex-dev/workos
```

## Configuration files

### convex/auth.config.ts

WorkOS issues JWTs from two different issuers. Configure both:

```typescript
const clientId = process.env.WORKOS_CLIENT_ID;

export default {
  providers: [
    {
      type: "customJwt",
      issuer: "https://api.workos.com/",
      algorithm: "RS256",
      applicationID: clientId,
      jwks: `https://api.workos.com/sso/jwks/${clientId}`,
    },
    {
      type: "customJwt",
      issuer: `https://api.workos.com/user_management/${clientId}`,
      algorithm: "RS256",
      jwks: `https://api.workos.com/sso/jwks/${clientId}`,
    },
  ],
};
```

Key points:
- Both providers use the same JWKS endpoint
- First provider handles SSO authentication
- Second provider handles User Management (email, social login)
- The `applicationID` is only needed for the SSO provider

### Frontend setup (React/Vite)

```typescript
import { AuthKitProvider, useAuth } from "@workos-inc/authkit-react";
import { ConvexProviderWithAuthKit } from "@convex-dev/workos";
import { ConvexReactClient } from "convex/react";

const convex = new ConvexReactClient(import.meta.env.VITE_CONVEX_URL);
const redirectUri = import.meta.env.VITE_WORKOS_REDIRECT_URI;

createRoot(document.getElementById("root")!).render(
  <AuthKitProvider
    clientId={import.meta.env.VITE_WORKOS_CLIENT_ID}
    redirectUri={redirectUri}
  >
    <ConvexProviderWithAuthKit client={convex} useAuth={useAuth}>
      <App />
    </ConvexProviderWithAuthKit>
  </AuthKitProvider>
);
```

## Environment variables

### Frontend (.env.local)

```bash
VITE_CONVEX_URL=https://your-deployment.convex.cloud
VITE_WORKOS_CLIENT_ID=client_01XXXXXXXXXXXXXXXXXX
VITE_WORKOS_REDIRECT_URI=http://localhost:5173/callback
```

### Convex Dashboard

Set in Environment Variables section:

```
WORKOS_CLIENT_ID=client_01XXXXXXXXXXXXXXXXXX
```

### WorkOS Dashboard Configuration

1. **Redirect URIs**: Add callback URLs
   - `http://localhost:5173/callback` (development)
   - `https://yourdomain.netlify.app/components/callback` (Netlify production)
   - `https://yourdomain.com/callback` (custom domain production)

2. **CORS Origins**: Add allowed origins
   - `http://localhost:5173` (development)
   - `https://yourdomain.netlify.app` (Netlify production)
   - `https://yourdomain.com` (custom domain production)

3. **JWT Template**: Configure email claim (see JWT claims section)

### Netlify Deployment Configuration

When deploying to Netlify, configure environment variables in Netlify Dashboard:

1. Go to Site Settings > Environment Variables
2. Add the following variables:
   - `VITE_CONVEX_URL`: Your Convex deployment URL (e.g., `https://your-deployment.convex.cloud`)
   - `VITE_WORKOS_CLIENT_ID`: Your WorkOS Client ID
   - `VITE_WORKOS_REDIRECT_URI`: `https://yourdomain.netlify.app/components/callback`

Create a `netlify.toml` in your project root:

```toml
[build]
  command = "npm run build"
  publish = "dist"

[build.environment]
  NODE_VERSION = "20"

[[redirects]]
  from = "/*"
  to = "/index.html"
  status = 200
```

The SPA redirect rule ensures all routes serve `index.html` for client-side routing.

## Sign in implementation

Use `signIn()` directly from the AuthKit hook. Do not use `getSignInUrl()` which is deprecated.

```typescript
import { useAuth } from "@workos-inc/authkit-react";

function SignInButton() {
  const { signIn } = useAuth();
  
  return (
    <button
      onClick={() => {
        localStorage.setItem("authReturnPath", window.location.pathname);
        signIn();
      }}
    >
      Sign In
    </button>
  );
}
```

## Sign out implementation

```typescript
import { useAuth } from "@workos-inc/authkit-react";

function SignOutButton() {
  const { signOut } = useAuth();
  
  return (
    <button onClick={() => signOut()}>
      Sign Out
    </button>
  );
}
```

## OAuth callback handling

Handle the callback with proper loading state checks:

```typescript
function AuthCallback() {
  const { isLoading, user, signIn } = useAuth();
  const [authFailed, setAuthFailed] = useState(false);
  const hasAuthCode = useMemo(
    () => new URLSearchParams(window.location.search).has("code"),
    []
  );
  
  const returnPath = useMemo(() => {
    const storedPath = localStorage.getItem("authReturnPath");
    if (storedPath) {
      localStorage.removeItem("authReturnPath");
      return storedPath;
    }
    return "/";
  }, []);

  useEffect(() => {
    if (isLoading) return;

    if (user) {
      window.location.replace(returnPath);
      return;
    }

    if (hasAuthCode) {
      setAuthFailed(true);
      return;
    }

    window.location.replace(returnPath);
  }, [hasAuthCode, isLoading, returnPath, user]);

  return (
    <div>
      {authFailed ? (
        <button onClick={() => signIn()}>Try Again</button>
      ) : (
        <div>Finishing sign in...</div>
      )}
    </div>
  );
}
```

## Checking auth state in components

Use `useConvexAuth()` for auth state (not `useAuth()`) to ensure the Convex backend has validated the token:

```typescript
import { useConvexAuth, Authenticated, Unauthenticated } from "convex/react";

function MyComponent() {
  const { isLoading, isAuthenticated } = useConvexAuth();
  
  if (isLoading) return <div>Loading...</div>;
  
  return (
    <>
      <Authenticated>
        <AuthenticatedContent />
      </Authenticated>
      <Unauthenticated>
        <SignInPrompt />
      </Unauthenticated>
    </>
  );
}
```

## Accessing user identity in Convex functions

```typescript
import { query, QueryCtx } from "./_generated/server";
import { v } from "convex/values";

export const loggedInUser = query({
  args: {},
  returns: v.union(
    v.object({
      email: v.optional(v.string()),
      name: v.optional(v.string()),
      pictureUrl: v.optional(v.string()),
    }),
    v.null()
  ),
  handler: async (ctx) => {
    const identity = await ctx.auth.getUserIdentity();
    if (!identity) {
      return null;
    }
    return {
      email: identity.email,
      name: identity.name,
      pictureUrl: identity.pictureUrl,
    };
  },
});
```

## Admin access check pattern

Check admin status based on email domain:

```typescript
import { query, QueryCtx, MutationCtx, ActionCtx } from "./_generated/server";
import { v } from "convex/values";

type AuthContext = QueryCtx | MutationCtx | ActionCtx;

export async function requireAdminIdentity(ctx: AuthContext) {
  const identity = await ctx.auth.getUserIdentity();
  if (!identity) {
    throw new Error("Authentication required");
  }
  const email = identity.email;
  if (!email?.endsWith("@yourdomain.com")) {
    throw new Error("Admin access required");
  }
  return identity;
}

export async function getAdminIdentity(ctx: AuthContext) {
  const identity = await ctx.auth.getUserIdentity();
  if (!identity) {
    return null;
  }
  const email = identity.email;
  if (!email?.endsWith("@yourdomain.com")) {
    return null;
  }
  return identity;
}

export const isAdmin = query({
  args: {},
  returns: v.boolean(),
  handler: async (ctx) => {
    const identity = await ctx.auth.getUserIdentity();
    if (!identity) {
      return false;
    }
    const email = identity.email;
    if (!email) {
      return false;
    }
    return email.endsWith("@yourdomain.com");
  },
});
```

## JWT claims configuration

WorkOS JWT templates do not include email by default. Configure in WorkOS Dashboard:

1. Go to WorkOS Dashboard > Authentication > JWT Templates
2. Edit the default template
3. Add required claims:

```json
{
  "email": "{{user.email}}",
  "name": "{{user.first_name}} {{user.last_name}}",
  "picture": "{{user.profile_picture_url}}"
}
```

After configuration, `ctx.auth.getUserIdentity()` returns:

```typescript
{
  tokenIdentifier: "https://api.workos.com/user_management/client_xxx|user_yyy",
  subject: "user_yyy",
  issuer: "https://api.workos.com/user_management/client_xxx",
  email: "user@example.com",
  name: "User Name",
  pictureUrl: "https://..."
}
```

## Production vs development environments

### Different Client IDs

Use environment variables to switch between environments:

```typescript
// convex/auth.config.ts
const clientId = process.env.WORKOS_CLIENT_ID;
```

Set different values in:
- `.env.local` for local development
- `.env.production` for Netlify builds (or Netlify Dashboard environment variables)
- Convex Dashboard for each deployment (dev/prod)

### WorkOS API Key formats

- Development: `sk_test_...`
- Production: `sk_live_...`

### Client ID format

Both environments use: `client_01XXXXXXXXXXXXXXXXXX`

### Netlify vs Local Development URLs

| Environment | Redirect URI | CORS Origin |
|-------------|--------------|-------------|
| Local Dev | `http://localhost:5173/callback` | `http://localhost:5173` |
| Netlify | `https://yourdomain.netlify.app/components/callback` | `https://yourdomain.netlify.app` |
| Custom Domain | `https://yourdomain.com/callback` | `https://yourdomain.com` |

Note: When hosting on Netlify with a `/components` base path, ensure your callback URL includes the full path.

## Checklist for new integration

- [ ] Install `@workos-inc/authkit-react` and `@convex-dev/workos`
- [ ] Set `WORKOS_CLIENT_ID` in Convex dashboard environment variables
- [ ] Set `VITE_WORKOS_CLIENT_ID` in `.env.local`
- [ ] Set `VITE_WORKOS_REDIRECT_URI` in `.env.local`
- [ ] Configure JWT template in WorkOS dashboard with email claim
- [ ] Add redirect URI(s) in WorkOS dashboard (localhost + production)
- [ ] Add CORS origins in WorkOS dashboard
- [ ] Configure both JWT providers in `convex/auth.config.ts`
- [ ] Run `npx convex dev` to sync auth config
- [ ] Handle OAuth callback with proper loading state checks
- [ ] Use `signIn()` directly, not `getSignInUrl()`
- [ ] Test admin access after user logs in with correct email domain

## Checklist for Netlify deployment

- [ ] Create `netlify.toml` with build command and SPA redirect
- [ ] Set environment variables in Netlify Dashboard (VITE_CONVEX_URL, VITE_WORKOS_CLIENT_ID, VITE_WORKOS_REDIRECT_URI)
- [ ] Add Netlify callback URL to WorkOS Redirect URIs
- [ ] Add Netlify origin to WorkOS CORS Origins
- [ ] Test callback flow after deployment

## Source links

- Convex + WorkOS AuthKit: https://docs.convex.dev/auth/authkit/
- WorkOS AuthKit: https://workos.com/docs/authkit
- AuthKit React SDK: https://workos.com/docs/sdks/authkit-react
- WorkOS API Reference: https://workos.com/docs/reference
- Auto provisioning: https://docs.convex.dev/auth/authkit/auto-provision
- Troubleshooting: https://docs.convex.dev/auth/authkit/troubleshooting
- Convex Auth Functions: https://docs.convex.dev/auth/functions-auth

Related Skills

workos-convex-debug

6
from get-convex/components-submissions-directory

Debug and troubleshoot WorkOS AuthKit authentication issues with Convex. Use when authentication fails, JWT validation errors occur, user identity returns null, email claims are missing, admin access checks fail, or sign in button does not work. Supports Netlify deployment.

convex-scale-optimization

6
from get-convex/components-submissions-directory

Patterns for scaling read-heavy Convex apps to millions of users. Use when optimizing bandwidth, reducing query costs, fixing slow queries, creating digest tables, replacing reactive subscriptions with one-shot fetches, adding compound indexes, debouncing writes, rate-controlling backfills, or running npx convex insights. Trigger when users mention "scale", "bandwidth", "performance", "optimize", "slow queries", "expensive queries", "digest table", "denormalize", or "thundering herd" in the context of Convex.

convex-design-system

6
from get-convex/components-submissions-directory

Convex UI component patterns from the live Storybook preview. Use when building React components, forms, modals, navigation, feedback states, or app layouts that should match the current Convex design system. Applies to both shared primitives and dashboard style product UI.

robel-auth

6
from get-convex/components-submissions-directory

Integrate and maintain Robelest Convex Auth in apps by always checking upstream before implementation. Use when adding auth setup, updating auth wiring, migrating between upstream patterns, or troubleshooting @robelest/convex-auth behavior across projects.

convex-self-hosting

6
from get-convex/components-submissions-directory

Integrate Convex static self hosting into existing apps using the latest upstream instructions from get-convex/self-hosting every time. Use when setting up upload APIs, HTTP routes, deployment scripts, migration from external hosting, or troubleshooting static deploy issues across React, Vite, Next.js, and other frontends.

convex-return-validators

6
from get-convex/components-submissions-directory

Guide for when to use and when not to use return validators in Convex functions. Use this skill whenever the user is writing Convex queries, mutations, or actions and needs guidance on return value validation. Also trigger when the user asks about Convex type safety, runtime validation, AI-generated Convex code, Convex AI rules, Convex security best practices, or when they're debugging return type issues in Convex functions. Trigger this skill when users mention "validators", "returns", "return type", or "exact types" in the context of Convex development. Also trigger when writing or reviewing Convex AI rules or prompts that instruct LLMs how to write Convex code.

convex-doctor

6
from get-convex/components-submissions-directory

Static analysis checklist for Convex backends covering 72 rules across security, performance, correctness, schema, architecture, configuration, and client-side patterns. Use when writing, reviewing, or auditing Convex code. Trigger on mentions of "convex-doctor", "health score", "static analysis", "anti-patterns", "audit convex", or before shipping backend changes.

convex

6
from get-convex/components-submissions-directory

Routes general Convex requests to the right project skill. Use when the user asks which Convex skill to use or gives an underspecified Convex app task.

convex-setup-auth

6
from get-convex/components-submissions-directory

Sets up Convex auth, identity mapping, and access control. Use for login, auth providers, users tables, protected functions, or roles in a Convex app.

convex-quickstart

6
from get-convex/components-submissions-directory

Creates or adds Convex to an app. Use for new Convex projects, npm create convex@latest, frontend setup, env vars, or the first npx convex dev run.

convex-performance-audit

6
from get-convex/components-submissions-directory

Audits Convex performance for reads, subscriptions, write contention, and function limits. Use for slow features, insights findings, OCC conflicts, or read amplification.

convex-migration-helper

6
from get-convex/components-submissions-directory

Plans Convex schema and data migrations with widen-migrate-narrow and @convex-dev/migrations. Use for breaking schema changes, backfills, table reshaping, or zero-downtime rollouts.