Docs

Integrate InstantDB with Clerk

You will learn the following:

  • Configure your Clerk session token to include the email claim.
  • Configure InstantDB to use your Clerk application.
  • Integrate InstantDB into your Clerk application.

Important

See the demo repo for a full example of how to integrate InstantDB with Clerk in a Next.js app.

Integrating InstantDB with Clerk gives you the benefits of using an InstantDB database while leveraging Clerk's authentication, prebuilt components, and webhooks.

This guide will walk you through the steps to integrate InstantDB with Clerk in your Next.js app.

Configure your Clerk session token

InstantDB uses Clerk's session token to authenticate users. To use InstantDB with Clerk, you need to include the email claim in your session token.

  1. Navigate to the Clerk Dashboard.
  2. In the navigation sidebar, select Sessions.
  3. In the Customize session token section, select Edit.
  4. Add the email claim to your session token:
    {
      "email": "{{user.primary_email_address}}"
    }

You can have additional claims as long as the email claim is set to {{user.primary_email_address}}.

Get your Clerk publishable key

  1. Navigate to the Clerk Dashboard.
  2. In the navigation sidebar, select API Keys.
  3. In the Quick Copy section, copy your Clerk publishable key.

Configure InstantDB

  1. Navigate to the InstantDB dashboard.
  2. Select the Auth tab.
  3. Select Setup Clerk.
  4. Add the publishable key you copied in the previous step.
  5. Confirm the The session token has the "email" claim. message.
  6. Select Add Clerk app.

Install the InstantDB library

Add the InstantDB library to your project.

terminal
npm i @instantdb/react
terminal
yarn add @instantdb/react
terminal
pnpm add @instantdb/react

Integrate InstantDB to your Clerk application

To sign in to InstantDB with Clerk, you need to:

  • Initialize InstantDB with your Clerk publishable key.
  • Use Clerk's getToken() helper to get the session for the user that is signed in to Clerk.
  • Pass the session to InstantDB's db.auth.signInWithIdToken() method in order to sign in to InstantDB. When you call db.auth.signInWithIdToken(), InstantDB will verify that the session was signed by your Clerk app. If verified, InstantDB uses the email in the session's claims to sign in, look up your user, or create a new one.

To sign out of the application, call both InstantDB's db.auth.signOut() method and Clerk's signOut() method.

app/page.tsx
'use client'

import { useAuth } from '@clerk/nextjs'
import { init } from '@instantdb/react'
import { useEffect } from 'react'

// Insert your app ID from https://instantdb.com/dash
const APP_ID = '<YOUR_APP_ID>'
// Use the Clerk client name that you set in the "Auth" tab of the InstantDB dashboard
const CLERK_CLIENT_NAME = 'clerk'

// Initialize InstantDB
const db = init({ appId: APP_ID })

export default function Page() {
  // Use `useAuth()` to get the `getToken()` and `signOut()` methods
  const { getToken, signOut } = useAuth()

  // Create a function to sign in to InstantDB with the Clerk token
  const signInToInstantWithClerkToken = async () => {
    // Get the JWT (token) from Clerk for your signed-in user
    const token = await getToken()

    if (!token) {
      return
    }

    // Create a long-lived session with InstantDB for your Clerk user
    // It will look up the user by email or create a new user with
    // the email provided in the session token
    db.auth.signInWithIdToken({
      clientName: CLERK_CLIENT_NAME,
      idToken: token,
    })
  }

  useEffect(() => {
    signInToInstantWithClerkToken()
  }, [])

  const { isLoading, user, error } = db.useAuth()

  if (isLoading) {
    return <div>Loading...</div>
  }

  if (error) {
    return <div>Error signing in to InstantDB! {error.message}</div>
  }

  if (user) {
    return (
      <div>
        <p>Signed in with InstantDB through Clerk!</p>{' '}
        <button
          onClick={() => {
            // First sign out of InstantDB to clear the InstantDB session
            db.auth.signOut().then(() => {
              // Then, sign out of Clerk to clear the Clerk session
              signOut()
            })
          }}
        >
          Sign out
        </button>
      </div>
    )
  }
  return (
    <div>
      <button onClick={signInToInstantWithClerkToken}>Sign in to InstantDB</button>
    </div>
  )
}

Feedback

What did you think of this content?

Last updated on