@convex-dev/workos-authkit

中文文档
0.3.0发布于 2026/10/28Apache-2.0TypeScriptES Module近 30 天下载 29.3万

A WorkOS AuthKit component for Convex.

原始使用文档
文档目录12 节
  1. Prerequisites
  2. Configure webhooks
  3. Installation
  4. Custom domain
  5. Usage
  6. Events
  7. Additional event types
  8. User data
  9. Backfilling existing users
  10. Actions
  11. Configuration
  12. Usage

Convex WorkOS AuthKit

npm version

This component is the official way to integrate WorkOS AuthKit authentication with your Convex project.

Features:

  • Sync user data from WorkOS to your Convex database reliably and durably.
  • Respond to events with Convex functions.
  • Backfill existing WorkOS users when adding the component to an existing app.

See example for a demo of how to incorporate this component into your application.

Open a GitHub issue with any feedback or bugs you find.

Prerequisites

Follow the Convex WorkOS AuthKit guide to set up a working project with WorkOS AuthKit.

Then follow the steps below to set up user data syncing and event handling.

Configure webhooks

User data syncing requires webhooks to be configured in your WorkOS project.

Select Webhooks from the left sidebar in your WorkOS project, and create a new webhook with the following settings:

  • Endpoint URL: https://<your-convex-deployment>.convex.site/workos/webhook
  • Events: user.created, user.updated, user.deleted

Webhook configuration

Copy the webhook secret and add it to your environment variables as WORKOS_WEBHOOK_SECRET. Webhook header

npx convex env set WORKOS_WEBHOOK_SECRET=<your-webhook-secret>

Installation

First, add @convex-dev/workos-authkit to your Convex project:

npm install @convex-dev/workos-authkit

Then, install the component within your convex/convex.config.ts file:

// convex/convex.config.ts
import workOSAuthKit from "@convex-dev/workos-authkit/convex.config";
import { defineApp } from "convex/server";

const app = defineApp();
app.use(workOSAuthKit);
export default app;

Create a Convex AuthKit client within your convex/ folder, and point it to the installed component:

// convex/auth.ts
import { AuthKit } from "@convex-dev/workos-authkit";
import { components } from "./_generated/api";
import type { DataModel } from "./_generated/dataModel";

export const authKit = new AuthKit<DataModel>(components.workOSAuthKit);

Finally, register component webhook routes in convex/http.ts:

import { httpRouter } from "convex/server";
import { authKit } from "./auth";

const http = httpRouter();
authKit.registerRoutes(http);
export default http;

Custom domain

If you've configured a custom WorkOS authentication API domain, pass it as apiHostname when constructing the AuthKit client. This routes the WorkOS SDK through your domain and updates the JWT issuer and JWKS URLs to match.

// convex/auth.ts
export const authKit = new AuthKit<DataModel>(components.workOSAuthKit, {
  apiHostname: "auth.example.com",
});

Usage

User create/update/delete in WorkOS will be automatically synced by the component.

Use the getAuthUser component method to get the current authenticated user object:

export const getCurrentUser = query({
  args: {},
  handler: async (ctx, _args) => {
    const user = await authKit.getAuthUser(ctx);
    return user;
  },
});

Events

The AuthKit component can be configured to handle events from WorkOS. This is useful for running code when a user is created, updated, or deleted in WorkOS, or in response to any other provided event.

By default the component will handle the following events:

  • user.created
  • user.updated
  • user.deleted

The user.deleted handler also runs when the component never stored the user, for example when WorkOS delivers the deletion before the creation. event.data is then the webhook payload as sent, so only id is guaranteed, even though it is typed as a full user. When the component has the user stored, its fields fill any gaps.

If your app has no record of the user, be sure to return rather than throw. Throwing fails the webhook and rolls back the component's record of the deletion, so a user.created that arrives before WorkOS retries recreates the user in the component and your app.

// convex/auth.ts
import { AuthKit, type AuthFunctions } from "@convex-dev/workos-authkit";
import { components, internal } from "./_generated/api";
import type { DataModel } from "./_generated/dataModel";

// Get a typed object of internal Convex functions exported by this file
const authFunctions: AuthFunctions = internal.auth;

const authKit = new AuthKit<DataModel>(components.workOSAuthKit, {
  authFunctions,
});

// create `authKitEvent` as a named export
export const { authKitEvent } = authKit.events({
  "user.created": async (ctx, event) => {
    // ctx is a mutation context and event.data is typed
    await ctx.db.insert("todoLists", {
      name: `${event.data.firstName}'s Todo List`,
      userId: event.data.id,
    });
  },
});

Additional event types

The component can handle any WorkOS event type. WorkOS docs provide a complete list of events. To handle an additional event type, select it in your webhook configuration and add a handler for it.

// convex/auth.ts
import { AuthKit, type AuthFunctions } from "@convex-dev/workos-authkit";
import { components, internal } from "./_generated/api";
import type { DataModel } from "./_generated/dataModel";

const authFunctions: AuthFunctions = internal.auth;

const authKit = new AuthKit<DataModel>(components.workOSAuthKit, {
  authFunctions,
});

export const { authKitEvent } = authKit.events({
  "session.created": async (ctx, event) => {
    // do something with the session data
  },
  "session.revoked": async (ctx, event) => {
    // do something with the session data
  },
});

User data

Most apps will need to control their user schema and be able to query directly against a users table. The AuthKit component has it's own user table with user data from WorkOS. You can think of this as auth metadata for your users, but you'll likely want to extend this with additional data from your app.

A common pattern for this is to create your own users table with a reference to the AuthKit user table, using the user events to do any necessary syncing.

// convex/auth.ts
import { AuthKit, type AuthFunctions } from "@convex-dev/workos-authkit";
import { components, internal } from "./_generated/api";
import type { DataModel } from "./_generated/dataModel";

const authFunctions: AuthFunctions = internal.auth;

const authKit = new AuthKit<DataModel>(components.workOSAuthKit, {
  authFunctions,
});

export const { authKitEvent } = authKit.events({
  "user.created": async (ctx, event) => {
    await ctx.db.insert("users", {
      authId: event.data.id,
      email: event.data.email,
      name: `${event.data.firstName} ${event.data.lastName}`,
    });
  },
  "user.updated": async (ctx, event) => {
    const user = await ctx.db
      .query("users")
      .withIndex("authId", (q) => q.eq("authId", event.data.id))
      .unique();
    if (!user) {
      console.warn(`User not found: ${event.data.id}`);
      return;
    }
    await ctx.db.patch(user._id, {
      email: event.data.email,
      name: `${event.data.firstName} ${event.data.lastName}`,
    });
  },
  "user.deleted": async (ctx, event) => {
    const user = await ctx.db
      .query("users")
      .withIndex("authId", (q) => q.eq("authId", event.data.id))
      .unique();
    if (!user) {
      console.warn(`User not found: ${event.data.id}`);
      return;
    }
    await ctx.db.delete(user._id);
  },

  // Handle any event type
  "session.created": async (ctx, event) => {
    console.log("onCreateSession", event);
  },
});

Backfilling existing users

If you're adding this component to an app that already has users in WorkOS, you can backfill them into the component's user table. The backfill also fires user.created event handlers, so your app's own tables get populated too.

Export the backfill utility from your auth file:

// convex/auth.ts
export const { backfillUsers } = authKit.utils();

Then trigger it from the CLI or the Convex dashboard:

npx convex run auth:backfillUsers

The backfill processes users oldest-first. It's idempotent - if interrupted, just run it again and it will skip users that are already synced.

Actions

The AuthKit component can be configured to handle actions from WorkOS. Actions allow you to block user registration or authentication based on your own logic. Read more about actions in the WorkOS docs.

Configuration

  1. Configure actions in your WorkOS dashboard.
  2. Set the endpoint URL for your action(s) to https://<your-convex-deployment>.convex.site/workos/action
  3. Copy the action signing secret from the dashboard and set it in your environment variables as WORKOS_ACTION_SECRET.

Action configuration

Usage

Action handlers are defined using the actions method on the AuthKit component. AuthKit actions must return a response payload that allows or denies the action, so a response object is provided to the action handler with allow and deny methods.

// convex/auth.ts
import { AuthKit, type AuthFunctions } from "@convex-dev/workos-authkit";
import { components, internal } from "./_generated/api";
import type { DataModel } from "./_generated/dataModel";

const authFunctions: AuthFunctions = internal.auth;

const authKit = new AuthKit<DataModel>(components.workOSAuthKit, {
  authFunctions,
});

export const { authKitAction } = authKit.actions({
  authentication: async (_ctx, _action, response) => {
    return response.allow();
  },
  userRegistration: async (_ctx, action, response) => {
    if (action.userData.email.endsWith("@gmail.com")) {
      return response.deny("Gmail accounts are not allowed");
    }
    return response.allow();
  },
});

版本与发布记录

@convex-dev/workos-authkit 共发布 19 个版本,首次发布于 2025/11/28;过去 12 个月发布了 19 个版本。

版本发布日期距今
0.3.0latest2026/10/2813 天前
0.2.102026/09/281 个月前
0.2.92026/08/222 个月前
0.2.82026/08/222 个月前
0.2.72026/06/114 个月前
0.2.62026/05/285 个月前

关于 @convex-dev/workos-authkit 的常见问题

@convex-dev/workos-authkit 是什么?

A WorkOS AuthKit component for Convex.

如何安装 @convex-dev/workos-authkit?

在项目目录运行 npm install @convex-dev/workos-authkit,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:react(^18.3.1 || ^19.0.0)、convex(^1.29.3)、@workos-inc/node(^7.75.1 || ^8.0.0 || ^9.0.0 || ^10.0.0)、@workos-inc/authkit-react(^0.13.0 || ^0.16.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@convex-dev/workos-authkit 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@convex-dev/workos-authkit 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@convex-dev/workos-authkit 可以商用吗?

@convex-dev/workos-authkit 使用 Apache-2.0 许可。宽松许可:允许商业使用、修改和再分发,并附带明确的专利授权;分发时需保留许可与 NOTICE 文件,修改过的文件要注明改动。以上为概括,不构成法律意见,请以许可原文为准。

@convex-dev/workos-authkit 的下载量有多少?

根据 npm 官方下载统计,@convex-dev/workos-authkit 在 2026/10/11 – 2026/11/09 这 30 天内被下载 292,851 次,日均约 9,762 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@convex-dev/workos-authkit 还在维护吗?

最新版本 0.3.0 发布于 2026/10/28(13 天前);至今共发布 19 个版本,其中过去 12 个月发布了 19 个;首次发布于 2025/11/28。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。