Skip to content

Authentication with Clerk

Clerk is a hosted sign-in service: it stores accounts, sends the emails and texts, and gives you a dashboard. You keep Pulze's own pages and drive them with Clerk's "custom flow" API.

Read Authentication first: it explains the adapter these steps fill in.

Time: about 45 minutes.

Versions: this guide uses Clerk's current custom-flow API, which needs @clerk/nextjs 7 or newer (Next.js) or @clerk/react 6 or newer (Vite). Older versions use different method names (signIn.create, attemptFirstFactor, setActive).

What Clerk covers

Pulze feature Clerk Notes
Email + password ✓
Google, GitHub, Apple ✓ Needs the /sso-callback page (step 4)
Magic link ✓ "email verification link" Finishes in the tab that asked for it
Forgot / reset password ✓ code-based Set resetWith: "code" (step 2)
Two-step: app, SMS, backup ✓ Turn on in the Clerk dashboard (paid plans)
SSO (SAML / OIDC) ✓ "enterprise connections" Paid plans
Passkey on lock screen ✓
Workspaces and invites ✓ Organizations Turn on Organizations in the dashboard

Check Clerk's pricing page for which features are on your plan.

1. Create the Clerk app

  1. Sign up at clerk.com and create an application. Pick Email, Password, and the social providers that match siteConfig.auth.providers.
  2. Configure › Organizations: turn on Organizations (for sign-up steps 2 and 3).
  3. Configure › Paths: set the sign-in page to /sign-in and sign-up to /sign-up, so Clerk never sends people to its own hosted pages.
  4. Copy the two keys from API keys.

2. Install and configure

Next.js:

pnpm add @clerk/nextjs
# .env.local (never commit it)
NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY=pk_test_...
CLERK_SECRET_KEY=sk_test_...
NEXT_PUBLIC_CLERK_SIGN_IN_URL=/sign-in
NEXT_PUBLIC_CLERK_SIGN_UP_URL=/sign-up

Vite:

pnpm add @clerk/react
# .env.local
VITE_CLERK_PUBLISHABLE_KEY=pk_test_...

Clerk emails a 6-digit code for password resets, not a link. Tell Pulze in site.config.ts:

auth: {
  // …
  resetWith: "code",
},

Forgot password now asks for the code on its second screen and moves on to "Set a new password".

3. Wrap the app and add the bridge

Clerk's API comes from React hooks, while Pulze's adapter is a plain object. A tiny bridge component reads the hooks and hands them to the adapter.

Create clerk-bridge.tsx in the app (Next.js: app/clerk-bridge.tsx; Vite: src/clerk-bridge.tsx):

"use client"

import { useClerk, useSignIn, useSignUp } from "@clerk/nextjs" // Vite: "@clerk/react"
import { clerkRefs } from "@pulze/data"

/** Keeps the adapter pointed at Clerk's current objects. Renders nothing. */
export function ClerkBridge() {
  clerkRefs.clerk = useClerk()
  clerkRefs.signIn = useSignIn().signIn
  clerkRefs.signUp = useSignUp().signUp
  return null
}

Next.js: in app/layout.tsx, wrap the body in ClerkProvider and add the bridge:

import { ClerkProvider } from "@clerk/nextjs"

import { ClerkBridge } from "./clerk-bridge"

// inside RootLayout's <body>:
;<ClerkProvider>
  <ClerkBridge />
  {/* the existing providers and {children} */}
</ClerkProvider>

Vite: in src/main.tsx:

import { ClerkProvider } from "@clerk/react"

import { ClerkBridge } from "./clerk-bridge"

;<ClerkProvider publishableKey={import.meta.env.VITE_CLERK_PUBLISHABLE_KEY}>
  <ClerkBridge />
  {/* the existing app */}
</ClerkProvider>

4. The social sign-in return page

Google, GitHub, Apple and SSO leave your site and come back to /sso-callback, where Clerk finishes the sign-in.

Next.js: create app/sso-callback/page.tsx:

"use client"

import { HandleSSOCallback } from "@clerk/nextjs"
import { useRouter } from "next/navigation"

export default function SsoCallback() {
  const router = useRouter()
  return (
    <HandleSSOCallback
      navigateToApp={() => router.push("/")}
      navigateToSignIn={() => router.push("/sign-in")}
      navigateToSignUp={() => router.push("/sign-up")}
    />
  )
}

Vite: add the same component as a route in src/router.tsx, using useNavigate() from React Router and HandleSSOCallback from @clerk/react.

Add /sso-callback to the public list in proxy.ts (step 6).

5. Write the adapter

Create src/data/auth/clerk.ts:

import { siteConfig } from "@pulze/config"

import { setPendingEmail } from "./pending"
import { AuthError, type AuthAdapter, type AuthNext } from "./types"

/* eslint-disable @typescript-eslint/no-explicit-any -- Clerk's objects, set by ClerkBridge */
export const clerkRefs: { clerk: any; signIn: any; signUp: any } = {
  clerk: null,
  signIn: null,
  signUp: null,
}

const CALLBACK = { redirectCallbackUrl: "/sso-callback", redirectUrl: "/" }

/** Which second step is waiting: app code, text message or email code. */
let second: "totp" | "sms" | "email" = "totp"

/** Turns a Clerk error into the screens Pulze knows. */
function check(error: any, fallback: AuthError["code"] = "unknown") {
  if (!error) return
  const code: string = error.code ?? error.errors?.[0]?.code ?? ""
  const message: string =
    error.longMessage ??
    error.errors?.[0]?.longMessage ??
    error.message ??
    "Something went wrong."
  if (code === "form_password_incorrect" || code === "form_identifier_not_found")
    throw new AuthError("That email and password don't match.", "wrong-password")
  if (code === "form_identifier_exists")
    throw new AuthError("There's already an account with this email.", "email-taken")
  if (code === "form_code_incorrect")
    throw new AuthError(
      "That code isn't right.",
      fallback === "link-expired" ? "link-expired" : "wrong-code"
    )
  if (code === "verification_expired")
    throw new AuthError("This code has expired. Ask for a new one.", "link-expired")
  if (code === "too_many_requests" || code === "user_locked")
    throw new AuthError("Too many tries. Wait a few minutes.", "too-many-tries", 0)
  throw new AuthError(message, fallback)
}

/** After the first step: finish, or move to the two-step page. */
async function next(email: string): Promise<AuthNext> {
  const { signIn } = clerkRefs
  if (signIn.status === "complete") {
    await signIn.finalize()
    return { next: "done" }
  }
  if (signIn.status === "needs_client_trust") {
    // New device: Clerk emails a code before letting the person in.
    await signIn.mfa.sendEmailCode()
    second = "email"
  } else if (signIn.status === "needs_second_factor") {
    second = "totp"
  } else {
    throw new AuthError("Something went wrong. Try again.", "unknown")
  }
  setPendingEmail(email)
  return { next: "two-step", email }
}

export const clerkAuth: AuthAdapter = {
  async currentUser() {
    const u = clerkRefs.clerk?.user
    if (!u) return null
    return {
      id: u.id,
      name: u.fullName ?? "",
      email: u.primaryEmailAddress?.emailAddress ?? "",
      hue: 262,
    }
  },

  async signIn({ email, password }) {
    // "Keep me signed in": Clerk sessions follow the lifetime set in the dashboard.
    const { error } = await clerkRefs.signIn.password({ emailAddress: email, password })
    check(error)
    return next(email)
  },

  async signInWithProvider(provider) {
    const { error } = await clerkRefs.signIn.sso({
      strategy: `oauth_${provider}`,
      ...CALLBACK,
    })
    check(error)
    return { next: "done" } // the browser is already on its way to the provider
  },

  async signInWithSso(email) {
    const { error } = await clerkRefs.signIn.sso({
      strategy: "enterprise_sso",
      identifier: email,
      ...CALLBACK,
    })
    check(error)
    return { next: "done" }
  },

  async sendMagicLink(email) {
    const { signIn } = clerkRefs
    const { error } = await signIn.emailLink.sendLink({
      emailAddress: email,
      verificationUrl: `${window.location.origin}/sign-in`,
    })
    check(error)
    // When the link is clicked (in any tab), this tab finishes and opens the app.
    void signIn.emailLink.waitForVerification().then(async () => {
      if (signIn.status === "complete") {
        await signIn.finalize()
        window.location.assign("/")
      }
    })
  },

  async signUp({ firstName, lastName, email, password }) {
    const { signUp } = clerkRefs
    check((await signUp.password({ emailAddress: email, password })).error)
    check((await signUp.update({ firstName, lastName })).error)
    // Clerk checks the email before creating the account. Pulze's sign-up has
    // no code screen, so send a link and wait here until it's clicked.
    check(
      (
        await signUp.verifications.sendEmailLink({
          verificationUrl: `${window.location.origin}/sign-up`,
        })
      ).error
    )
    check((await signUp.verifications.waitForEmailLinkVerification()).error)
    if (signUp.status === "complete") await signUp.finalize()
  },

  async createWorkspace({ name, slug }) {
    const { clerk } = clerkRefs
    const org = await clerk.createOrganization({ name, slug })
    await clerk.setActive({ organization: org.id })
  },

  async inviteTeam(emails) {
    const org = clerkRefs.clerk.organization
    for (const emailAddress of emails)
      await org.inviteMember({ emailAddress, role: "org:member" })
  },

  async sendPasswordReset(email) {
    const { signIn } = clerkRefs
    check((await signIn.create({ identifier: email })).error)
    check((await signIn.resetPasswordEmailCode.sendCode()).error)
  },

  /** With resetWith "code", the "token" is the code the person typed. */
  async checkResetToken(token) {
    const { signIn } = clerkRefs
    check(
      (await signIn.resetPasswordEmailCode.verifyCode({ code: token })).error,
      "link-expired"
    )
    return { email: signIn.identifier ?? "" }
  },

  async resetPassword(_token, password) {
    const { signIn } = clerkRefs
    check(
      (
        await signIn.resetPasswordEmailCode.submitPassword({
          password,
          signOutOfOtherSessions: true,
        })
      ).error
    )
    if (signIn.status === "complete") await signIn.finalize()
  },

  async verifyCode(code) {
    const { mfa } = clerkRefs.signIn
    const { error } =
      second === "sms"
        ? await mfa.verifyPhoneCode({ code })
        : second === "email"
          ? await mfa.verifyEmailCode({ code })
          : await mfa.verifyTOTP({ code })
    check(error, "wrong-code")
    setPendingEmail(null)
    await clerkRefs.signIn.finalize()
  },

  async verifyBackupCode(code) {
    check((await clerkRefs.signIn.mfa.verifyBackupCode({ code })).error, "wrong-code")
    setPendingEmail(null)
    await clerkRefs.signIn.finalize()
  },

  async sendCodeBySms() {
    check((await clerkRefs.signIn.mfa.sendPhoneCode()).error)
    second = "sms"
    return "your phone"
  },

  /** Clerk can't check a password from the browser once signed in; see step 7. */
  async unlock(password) {
    const res = await fetch("/api/unlock", {
      method: "POST",
      body: JSON.stringify({ password }),
    })
    if (!res.ok) throw new AuthError("That's not your password.", "wrong-password")
  },

  async unlockWithPasskey() {
    throw new AuthError(
      `Use your password, or contact ${siteConfig.support.email}.`,
      "unknown"
    )
  },

  async signOut() {
    await clerkRefs.clerk.signOut()
  },
}

Switch Pulze to it in src/data/auth/index.ts, and export the refs for the bridge:

import { clerkAuth } from "./clerk"
export { clerkRefs } from "./clerk"
export const auth: AuthAdapter = clerkAuth

6. Protect the app pages (Next.js)

Create proxy.ts next to app/:

import { clerkMiddleware, createRouteMatcher } from "@clerk/nextjs/server"

const isPublic = createRouteMatcher([
  "/sign-in(.*)",
  "/sign-up(.*)",
  "/forgot-password",
  "/reset-password",
  "/two-step",
  "/sso-callback",
  "/maintenance",
])

export const proxy = clerkMiddleware(async (auth, request) => {
  if (!isPublic(request)) await auth.protect()
})

export const config = {
  matcher: [
    "/((?!_next|[^?]*\\.(?:html?|css|js(?!on)|jpe?g|webp|png|gif|svg|ttf|woff2?|ico)).*)",
    "/(api|trpc)(.*)",
  ],
}

Signed-out visitors go to NEXT_PUBLIC_CLERK_SIGN_IN_URL (/sign-in). In route handlers and server actions, check again before returning private data:

import { auth } from "@clerk/nextjs/server"

const { userId } = await auth()
if (!userId) return new Response("Signed out", { status: 401 })

Vite: use the route guard in Authentication. Your API checks Clerk's session token with @clerk/backend.

7. The lock screen (Next.js)

To check the password on the lock screen, Pulze asks your server, which asks Clerk. Create app/api/unlock/route.ts:

import { auth, clerkClient } from "@clerk/nextjs/server"

export async function POST(request: Request) {
  const { userId } = await auth()
  if (!userId) return new Response(null, { status: 401 })
  const { password } = await request.json()
  try {
    const client = await clerkClient()
    await client.users.verifyPassword({ userId, password })
    return new Response(null, { status: 204 })
  } catch {
    return new Response(null, { status: 401 })
  }
}

Vite: add the same endpoint to your API, or turn the idle lock off with lockAfterMinutes: 0.

8. Emails

Clerk sends every email (reset code, magic link, invite, verification). Edit the wording in the Clerk dashboard under Customization › Emails to match the email table. With resetWith: "code", the reset page no longer mentions a link.

9. Check it

  • Sign up: the confirmation email arrives; after clicking it, sign-up moves on to step 2, and the person appears under Users in Clerk.
  • Wrong password: "That email and password don't match."
  • Google (and each provider you kept) comes back through /sso-callback to the dashboard.
  • Forgot password: the code arrives, the page accepts it, the new password works.
  • Organizations: the workspace from sign-up step 2 shows in Clerk.
  • Open /apps/kanban in a private window: you're sent to /sign-in.

Troubleshooting

You see Fix
Cannot read properties of null (reading 'password') ClerkBridge isn't rendered, or is outside ClerkProvider (step 3).
Sent to accounts.<something>.dev to sign in Set NEXT_PUBLIC_CLERK_SIGN_IN_URL=/sign-in and the paths in the dashboard.
Social sign-in loops back to /sign-in /sso-callback is missing, or not in proxy.ts's public list.
"Two-step" never appears Turn on multi-factor in Configure › Multi-factor, and enrol from Settings › Security.
createOrganization fails Organizations are off in the dashboard.
Methods like signIn.password are undefined Your Clerk package is older than the versions at the top; update it, or follow Clerk's "legacy" guides.