On this page

Integrations

Convex Integration

Integrate Entro Auth with Convex.

Warning

@convex-dev/better-auth is built for Better Auth and names better-auth as a peer dependency. It has not been tested with Entro Auth, whose package has another name.

In this guide, we'll walk through the steps to integrate Entro Auth with Convex.

Prerequisites

Create a Convex project

To use Entro Auth with Convex, you need a Convex project. If you don’t have one, run the following command to create a new project. For more details, see the Convex documentation.

npm create convex@latest

# Choose user authentication:
# > none

Run convex dev

Running the CLI during setup will initialize your Convex deployment if it doesn't already exist, and keeps generated types current through the process. Keep it running.

npx convex dev

Install packages

Install Entro Auth and the Convex component for Entro Auth, and make sure you are using the latest version of Convex.

npm install @entro314labs/entro-auth @convex-dev/better-auth
Note

@convex-dev/better-auth is maintained by Convex.

Set environment variables

Generate a secret for encryption and generating hashes. Use the command below if you have openssl installed, or use npx @entro314labs/entro-auth-cli secret to generate one.

npx convex env set ENTRO_AUTH_SECRET=$(openssl rand -base64 32)

Add your site URL to your Convex deployment.

npx convex env set SITE_URL http://localhost:3000

Add environment variables to the .env.local file created by npx convex dev. It will be picked up by your framework dev server.

.env.local
# Deployment used by `npx convex dev`
CONVEX_DEPLOYMENT=dev:adjective-animal-123 # team: team-name, project: project-name

NEXT_PUBLIC_CONVEX_URL=https://adjective-animal-123.convex.cloud

# Same as NEXT_PUBLIC_CONVEX_URL but ends in .site
NEXT_PUBLIC_CONVEX_SITE_URL=https://adjective-animal-123.convex.site

# Your local site URL
NEXT_PUBLIC_SITE_URL=http://localhost:3000
Note

Since the Entro Auth instance runs on Convex, environment variables used by the auth instance should be configured through the Convex CLI or dashboard, not in .env.local.

e.g. ENTRO_AUTH_SECRET, GITHUB_CLIENT_ID, GITHUB_CLIENT_SECRET ...

Add Convex auth config

Add a convex/auth.config.ts file to configure Entro Auth as an authentication provider.

convex/auth.config.ts
import { getAuthConfigProvider } from "@convex-dev/better-auth/auth-config";
import type { AuthConfig } from "convex/server";

export default {
  providers: [getAuthConfigProvider()],
} satisfies AuthConfig;

Create the Entro Auth Convex Component

Convex components can be installed from NPM or a local folder. While the NPM version is available, this guide uses a local folder setup to unlock the full potential of Entro Auth.

Create the component definition

Create a convex/entroAuth/convex.config.ts file to define the component. This will signal to Convex that the convex/entroAuth directory is a locally installed component.

convex/entroAuth/convex.config.ts
import { defineComponent } from "convex/server";

const component = defineComponent("entroAuth");

export default component;

Register the component

Register the Entro Auth component in your Convex project.

convex/convex.config.ts
import { defineApp } from "convex/server";
import entroAuth from "./entroAuth/convex.config";

const app = defineApp();

app.use(entroAuth);

export default app;

Create a Entro Auth instance

Create a Entro Auth instance and initialize the component.

Note
  • This file is not yet complete before the next step.
  • Some TypeScript errors will show until you save the file.
convex/entroAuth/auth.ts
import { createClient } from "@convex-dev/better-auth";
import { convex } from "@convex-dev/better-auth/plugins";
import type { GenericCtx } from "@convex-dev/better-auth/utils";
import type { EntroAuthOptions } from "@entro314labs/entro-auth";
import { entroAuth } from "@entro314labs/entro-auth";
import { components } from "../_generated/api";
import type { DataModel } from "../_generated/dataModel";
import authConfig from "../auth.config";
import schema from "./schema";

// Entro Auth Component
export const authComponent = createClient<DataModel, typeof schema>(
  components.entroAuth,
  {
    local: { schema },
    verbose: false,
  },
);

// Entro Auth Options
export const createAuthOptions = (ctx: GenericCtx<DataModel>) => {
  return {
    appName: "My App",
    baseURL: process.env.SITE_URL,
    secret: process.env.ENTRO_AUTH_SECRET,
    database: authComponent.adapter(ctx),
    emailAndPassword: {
      enabled: true,
    },
    plugins: [convex({ authConfig })],
  } satisfies EntroAuthOptions;
};

// For `auth` CLI
export const options = createAuthOptions({} as GenericCtx<DataModel>);

// Entro Auth Instance
export const createAuth = (ctx: GenericCtx<DataModel>) => {
  return entroAuth(createAuthOptions(ctx));
};

Generate the schema

After configuring your Entro Auth instance, run the command below to generate convex/entroAuth/schema.ts.

npx @entro314labs/entro-auth-cli generate --config ./convex/entroAuth/auth.ts --output ./convex/entroAuth/schema.ts
Note

If you need to modify your Entro Auth instance, use this command to update the schema.

Export adapter functions

Export adapter functions for the Entro Auth component.

convex/entroAuth/adapter.ts
import { createApi } from "@convex-dev/better-auth";
import { createAuthOptions } from "./auth";
import schema from "./schema";

export const {
  create,
  findOne,
  findMany,
  updateOne,
  updateMany,
  deleteOne,
  deleteMany,
} = createApi(schema, createAuthOptions);

Create the Entro Auth client instance

Create the Entro Auth client instance for interacting with the Entro Auth server from your client.

lib/auth-client.ts
import { convexClient } from "@convex-dev/better-auth/client/plugins";
import { createAuthClient } from "@entro314labs/entro-auth/react";

export const authClient = createAuthClient({
  plugins: [convexClient()],
});

Configure Next.js server helpers

Configure a set of helper functions for authenticated SSR, server functions, and route handlers.

lib/auth-server.ts
import { convexBetterAuthNextJs } from "@convex-dev/better-auth/nextjs";

export const {
  handler,
  preloadAuthQuery,
  isAuthenticated,
  getToken,
  fetchAuthQuery,
  fetchAuthMutation,
  fetchAuthAction,
} = convexBetterAuthNextJs({
  convexUrl: process.env.NEXT_PUBLIC_CONVEX_URL!,
  convexSiteUrl: process.env.NEXT_PUBLIC_CONVEX_SITE_URL!,
});

Mount handlers

Register Entro Auth route handlers on your Convex deployment.

convex/http.ts
import { httpRouter } from "convex/server";
import { authComponent, createAuth } from "./entroAuth/auth";

const http = httpRouter();

authComponent.registerRoutes(http, createAuth);

export default http;

Set up route handlers to proxy auth requests from Next.js to your Convex deployment.

app/api/auth/[...all]/route.ts
import { handler } from "@/lib/auth-server";

export const { GET, POST } = handler;

Set up Convex client provider

Create a ConvexClientProvider component.

components/ConvexClientProvider.tsx
"use client";

import { ConvexBetterAuthProvider } from "@convex-dev/better-auth/react";
import { ConvexReactClient } from "convex/react";
import { authClient } from "@/lib/auth-client";

const convex = new ConvexReactClient(process.env.NEXT_PUBLIC_CONVEX_URL!);

export function ConvexClientProvider({
  children,
  initialToken,
}: {
  children: React.ReactNode;
  initialToken?: string | null;
}) {
  return (
    <ConvexBetterAuthProvider
      client={convex}
      authClient={authClient}
      initialToken={initialToken}
    >
      {children}
    </ConvexBetterAuthProvider>
  );
}

Wrap your app with the ConvexClientProvider component.

app/layout.tsx
import { ConvexClientProvider } from "@/components/ConvexClientProvider";
import { getToken } from "@/lib/auth-server";

export default async function RootLayout({
  children,
}: Readonly<{
  children: React.ReactNode;
}>) {
  const token = await getToken();
  return (
    <html>
      <body>
        <ConvexClientProvider initialToken={token}>
          {children}
        </ConvexClientProvider>
      </body>
    </html>
  );
}

Done 🎉

You're now ready to start using Entro Auth with Convex.


Usage

Create your functions

Entro Auth's auth.api methods would normally run in your server, but with Convex being your backend, these methods need to run in a Convex function. The Convex function can then be called from the client via hooks like useMutation or in server functions and other server code using one of the auth-server utilities like fetchAuthMutation.

Convex has a convention of creating functions in the convex/ directory. For example, you can create auth-related functions in the convex/auth.ts file like this:

convex/auth.ts
import { query } from "./_generated/server";

export const getCurrentUser = query({
  args: {},
  handler: async (ctx) => {
    const identity = await ctx.auth.getUserIdentity();
    return identity;
  },
});

// ... other functions

Using the Entro Auth client

You can use the authClient like the Entro Auth client normally.

app/sign-in/page.tsx
"use client";

import { Button } from "@/components/ui/button";
import { authClient } from "@/lib/auth-client";

const Page = () => {
  return (
    <div className="flex flex-col items-center justify-center h-screen">
      <Button
        onClick={async () => {
          await authClient.signIn.social({
            provider: "github",
            callbackURL: "/dashboard",
          });
        }}
      >
        Sign in with GitHub
      </Button>
    </div>
  );
};

export default Page;

Using the Convex React hooks

If you've created Convex functions, you can use the Convex React hooks to query or mutate data in the client side like the usual way.

app/dashboard/page.tsx
"use client";

import { useQuery } from "convex/react";
import { api } from "@/convex/_generated/api";

const Page = () => {
  const user = useQuery(api.auth.getCurrentUser);

  if (user === undefined) {
    return <div>Loading...</div>;
  }

  if (user === null) {
    return <div>Unauthorized</div>;
  }

  return (
    <div>
      <pre>{JSON.stringify(user, null, 2)}</pre>
    </div>
  );
};

export default Page;

Using the server helpers

You can use the server helpers to perform authentication related operations in the server side.

app/protected/page.tsx
import { isAuthenticated } from "@/lib/auth-server";

const Page = async () => {
  const hasToken = await isAuthenticated();
  if (!hasToken) {
    return <div>Unauthorized</div>;
  }

  return (
    <div>
      <p>Hello</p>
    </div>
  );
};

export default Page;

SSR with server components

Convex queries can be preloaded in server components and rendered in client components via preloadAuthQuery and usePreloadedAuthQuery.

Note

preloadAuthQuery is recommended for use when you want to handle different UI based on the data state, rather than for protecting resources.

Preloading in a server component:

app/landing/page.tsx
import { api } from "@/convex/_generated/api";
import { preloadAuthQuery } from "@/lib/auth-server";
import Header from "./header";

const Page = async () => {
  const preloadedUserQuery = await preloadAuthQuery(api.auth.getCurrentUser);

  return (
    <div>
      <Header preloadedUserQuery={preloadedUserQuery} />
    </div>
  );
};

export default Page;

Rendering preloaded data in a client component:

app/landing/header.tsx
"use client";

import { usePreloadedAuthQuery } from "@convex-dev/better-auth/nextjs/client";
import type { Preloaded } from "convex/react";
import Link from "next/link";
import { Button } from "@/components/ui/button";
import type { api } from "@/convex/_generated/api";

export const Header = ({
  preloadedUserQuery,
}: {
  preloadedUserQuery: Preloaded<typeof api.auth.getCurrentUser>;
}) => {
  const user = usePreloadedAuthQuery(preloadedUserQuery);
  return (
    <div>
      {user ? (
        <Button asChild>
          <Link href="/dashboard">Dashboard</Link>
        </Button>
      ) : (
        <Button asChild>
          <Link href="/sign-in">Sign in</Link>
        </Button>
      )}
    </div>
  );
};

export default Header;

Additional Resources