How to add PostHog and Clerk to your app: What businesses need to know

Projects

Ajoutez des services, générez des identifiants et gérez la facturation à partir de l’interface de ligne de commande (CLI), ou confiez cette tâche à votre agent.

En savoir plus 
  1. Introduction
  2. Key takeaways
  3. What are Clerk and PostHog?
    1. Why use Clerk and PostHog together?
  4. How do you set up Clerk and PostHog manually?
    1. Create the Clerk application
    2. Create the PostHog project
    3. Add the Clerk keys
    4. Add the PostHog key
    5. Configure redirects and domains
    6. Check your privacy requirements
  5. How do you set up Clerk and PostHog with Stripe Projects?
    1. Install the plugin
    2. Initialize your workspace
    3. Add Clerk
    4. Add PostHog
    5. Link an existing account
    6. Check on everything at once
    7. Add a teammate
    8. Rotate a compromised key
  6. How do you integrate Clerk authentication and PostHog analytics into your app?
    1. Install the SDKs
    2. Wrap your app in Clerk’s provider
    3. Access the current session
    4. Initialize PostHog once
    5. Identify the user after sign-in
    6. Carry identity to the backend
    7. Reset on sign-out
    8. Keep the systems separate
  7. What are the best practices when using Clerk?
  8. How Stripe Projects can help

Clerk is a developer tool that verifies who a user is, while PostHog handles what the user does once they have signed in. Connecting the two comes down to one identify() call that ties a Clerk user identification (ID) to PostHog’s event stream. This kind of setup is becoming common: in 2025, 54% of developers said they use six or more software applications or platforms for their work.

You can set up Clerk and PostHog manually or use Stripe Projects to simplify and speed up the process. Stripe Projects handles provisioning, credential storage, and billing for third-party infrastructure services.

Below, we’ll discuss what Clerk and PostHog do, how to get a Clerk secret key, and how to use Stripe Projects to add PostHog and Clerk to your app.

Key takeaways

  • Clerk manages identity and access, while PostHog manages behavior; the two connect only once you call identify() with a Clerk user identification (ID).

  • Stripe Projects provisions Clerk and PostHog from the command line interface (CLI), which stores credentials in an encrypted vault and syncs them to your local environment file automatically.

  • A successful Clerk sign-in doesn’t produce useful PostHog data on its own because the identify call still must run and the distinct ID must match across frontend and backend.

What are Clerk and PostHog?

Clerk handles authentication such as sign-up, sign-in, session tokens, multifactor authentication, magic links, and prebuilt sign-in and account menu components, so you don’t have to write password hashing or session cookies from scratch. Clerk also covers organizations for applications (apps) that need shared workspaces with role-based membership and gives each user a dashboard-visible profile that can be queried through its application programming interface (API).

PostHog captures events, records session replays, runs feature flags and A/B tests, and stores it all in a queryable warehouse. PostHog is more similar to a customer-data platform than a simple event tracker.

Why use Clerk and PostHog together?

Clerk and PostHog split work cleanly. Clerk issues the session token, exposes the user ID through useUser() on the client or auth() on the server, and decides which routes need a signed-in user. PostHog uses a default temporary ID to track anonymous session behavior. You can then tie the ID to a specific user profile once you identify them.

Once a session exists, call PostHog’s identify() method with the Clerk user ID. PostHog can then attach identity to behavior instead of guessing. Anonymous events from before sign-in merge into the identified profile, so an onboarding funnel or activation report shows the full picture instead of two disconnected records.

How do you set up Clerk and PostHog manually?

The manual setup path involves two dashboards and two sets of credentials. Each new environment, teammate, or redeploy repeats the same steps.

Create the Clerk application

Sign in to the Clerk Dashboard, create a new application, and choose which identifiers you’ll accept, such as email, phone, or username, along with any social providers to enable.

Create the PostHog project

Sign up at posthog.com, and then pick your region; that will determine your API host.

Add the Clerk keys

Copy the publishable key into NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY and the secret key into CLERK_SECRET_KEY. Keep the secret key set to server-side.

Add the PostHog key

Copy the project key into NEXT_PUBLIC_POSTHOG_KEY and pair it with NEXT_PUBLIC_POSTHOG_HOST, set to your region’s API host.

Configure redirects and domains

Add every domain your app on runs to Clerk’s allowed list so sign-in and sign-out flows resolve correctly in each environment.

Check your privacy requirements

Confirm your PostHog project’s data region meets the privacy rules your business must follow before you start capturing real user events.

How do you set up Clerk and PostHog with Stripe Projects?

Stripe Projects is a command line interface (CLI) plugin that provisions and manages third-party services from your terminal. Credentials get encrypted and stored in a project vault, and environment variables sync to your local .env file. Here’s the process:

Install the plugin

Run stripe plugin install projects to add the Projects commands to your Stripe CLI.

Initialize your workspace

Run stripe projects init my-app in your project directory. This creates a project vault, a shared state file, a .gitignore entry covering your credentials, and an AGENTS.md file that documents your setup for any AI coding agent working in the repo.

Add Clerk

Run stripe projects add clerk/auth, which authenticates with Clerk, provisions or links your application, and writes the publishable and secret keys to .env.

Add PostHog

Run stripe projects add posthog/analytics, which authenticates with PostHog, provisions or links your project, and writes the project key and host to .env.

Run stripe projects link <provider> if you have a Clerk or PostHog account. This associates it with your project so you don’t have to provision a new one.

Check on everything at once

Run stripe projects status to see every linked provider and its health in one table.

Add a teammate

Run stripe projects pull <project-id> so your teammate can clone the same setup onto a new machine by pulling credentials out of the vault. That way, you won’t have to paste keys into a chat thread.

Rotate a compromised key

Run stripe projects rotate clerk/auth to regenerate it, then stripe projects env --pull to refresh your local .env to match.

How do you integrate Clerk authentication and PostHog analytics into your app?

With both providers configured, integration happens at the code level. The two most important steps are installing the right software development kits (SDKs) and wiring up the identity handoff.

Install the SDKs

Add @clerk/nextjs—or the equivalent for your framework—and posthog-js for the client plus posthog-node if you want to capture events from server-side code, too.

Wrap your app in Clerk’s provider

Add clerkMiddleware() to protect any route that requires a signed-in user, and drop in Clerk’s prebuilt <SignIn />, <SignUp />, and <UserButton /> components for the interface.

Access the current session

Use useUser() on the client and auth() on the server when you need to know who’s signed in.

Initialize PostHog once

Set PostHog up in a top-level provider with your project key and host. You don’t need to reinitialize it on every page.

Identify the user after sign-in

Call posthog.identify(user.id, { email: user.primaryEmailAddress }) inside an effect that runs once per session, right after useUser() resolves to a signed-in user.

Carry identity to the backend

Pass the same distinct ID into server-side capture() calls rather than calling identify() a second time.

Reset on sign-out

Call posthog.reset() to unlink the browser from that identity before the next person uses the device.

Keep the systems separate

Let Clerk’s middleware decide whether a request gets through, and let PostHog’s identify call run independently after authorization.

What are the best practices when using Clerk?

A few habits can help prevent Clerk-related incidents.

Here’s what you need to know:

  • Separate your environments completely: Keep development and production instances and their environment files fully apart. A production secret key should never end up in a .env used for local development or vice versa.

  • Restrict who can see the secret key: Limit visibility in the Clerk Dashboard’s team settings to the smallest group of people who need it.

  • Rotate on any exposure: If a secret key shows up in a commit, a log, or a shared terminal session, rotate it immediately rather than waiting to see whether it’s a problem.

  • Cover every domain in your redirect list: Add preview deployments along with your production domain to Clerk’s allowed list. Sign-in attempts will fail with a redirect mismatch that gives no obvious explanation.

  • Keep personally identifiable information out of event properties: Don’t send full names, emails, or other identifying details into PostHog unless your privacy policy accounts for it.

  • Call identify() once per session: PostHog ignores duplicate calls with the same data, but unnecessary repeats still add noise to your usage.

  • Don’t assume a sign-in equals useful data: The identify call has to run, the distinct ID must match between frontend and backend, and someone has to define which events matter.

How Stripe Projects can help

Stripe Projects lets developers and their AI agents add services, generate credentials, and manage billing from the command line interface (CLI).

Stripe Projects helps you:

  • Provision third-party services from the command line: Use one workflow to add services, manage credentials, and upgrade plans, instead of different tools and workflows for every provider. Manage hosting, databases, auth, AI, and more without needing dashboards, config files, or infrastructure code.

  • Sync credentials automatically: Keep environment variables portable across local setups, machines, teammates, and agents—no copy-pasting application programming interface (API) keys.

  • Manage billing from the CLI or your coding agent: Set up billing details once and securely share them with third-party services. Upgrade and downgrade tiers, monitor usage, and manage subscriptions from the CLI.

Learn more about how Stripe Projects helps simplify app provisioning, or copy and paste this command into your terminal to get started today:

brew install stripe/stripe-cli/stripe && stripe plugin install projects && npx skills add https://github.com/stripe/ai --skill stripe-projects -y -g

Le contenu de cet article est fourni uniquement à des fins informatives et pédagogiques. Il ne saurait constituer un conseil juridique ou fiscal. Stripe ne garantit pas l'exactitude, l'exhaustivité, la pertinence, ni l'actualité des informations contenues dans cet article. Nous vous conseillons de consulter un avocat compétent ou un comptable agréé dans le ou les territoires concernés pour obtenir des conseils adaptés à votre situation particulière.

Plus d'articles

  • Un problème est survenu. Veuillez réessayer ou contacter le service d’assistance.

Envie de vous lancer?

Créez un compte et commencez à accepter des paiements rapidement, sans avoir à signer de contrat ni à fournir vos coordonnées bancaires. N'hésitez pas à nous contacter pour discuter de solutions personnalisées pour votre entreprise.
Payments

Payments

Acceptez des paiements en ligne, en personne et dans le monde entier, grâce à une solution de paiement adaptée à toutes les entreprises.

Documentation Payments

Trouvez un guide qui vous aidera à intégrer les API de paiement de Stripe.