Docs

You are viewing an archived version of the docs.Go to latest version

Integrate Firebase with Clerk

You will learn the following:

  • Use Clerk to authenticate access to your Firebase data.
  • Configure your Firebase Clerk integration.

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

Configure the integration

The Firebase integration enables you to use Clerk to generate a valid authentication token to send to Firebase Auth. This enables you to leverage Clerk's prebuilt components, auth provider options, and more, while accessing Firebase products like Firestore with a session validated by Firebase Auth.

To get enable the integration:

  1. Navigate to the Clerk Dashboard.
  2. In the sidebar, select Integrations.
  3. Toggle the Firebase integration on. The configuration modal will appear. Keep this open while you configure your Firebase project.

Next, configure your integration.

The recommended way to configure your integration is to use a service account key provided by Firebase in order to configure the integration automatically. To do so:

  1. In your Firebase project, visit the Service Accounts settings.
  2. Near the bottom of the page, select the Generate new private key button.
  3. In the modal that pops up, select the Generate key button to download the JSON file that contains your service account key.
  4. In the Clerk Dashboard, the Firebase configuration modal should still be open. Select the Upload service account key button and upload the JSON file you downloaded.
  5. The appropriate fields in the configuration modal will be filled in automatically. Select Apply changes to save your configuration.

Select the Configure manually tab above these instructions if you do not want to use a service account key.

If you want to manually configure your Firebase integration, you must provide Clerk with the following information about your Firebase project:

  • Service account email – Find this in your Firebase project's Google Cloud Console, or in the client_email field of your service account key JSON file.
  • Firestore project ID – Find this under Project Settings in the Firebase dashboard, or in the project_id field of your service account key JSON file.
  • Private Key – You can generate this manually, or find it in the private_key field of your service account key JSON file.
  • Firebase database URL (Optional) – To find this:
    • In the Firebase dashboard, select Realtime Database
    • Select the Data tab, and select the copy button to add the database URL to your clipboard.

Enable authentication in Firebase

To use Firebase auth, ensure authentication is enabled in your Firebase dashboard. To do so:

  1. Navigate to your Firebase dashboard.
  2. In the navigation sidebar, select the Build dropdown and select Authentication.
  3. Select Get started.
  4. Enable any sign-in method you want, such as Email/Password.

Add a Security Rule to your Firestore database (optional)

Adding the Cloud Firestore feature in your Firebase application is optional.

To use Firestore with Clerk, ensure that you have defined Security Rules that allow authenticated requests to access your database. For example:

service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if request.auth != null;
    }
  }
}

Get your Firebase config object

To connect to your Firebase app in your code, you need a config object from your Firebase project. To find it:

  1. Visit your Firebase project settings.
  2. In the Your apps section, there should be a code snippet that includes the firebaseConfig object. Copy this object. It should look similar to the following:
    const firebaseConfig = {
      apiKey: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
      authDomain: "clerk-example-xxxxx.firebaseapp.com",
      databaseURL: "https://clerk-example-xxxxx-default-xxxx.firebaseio.com",
      projectId: "clerk-test-xxxx",
      storageBucket: "clerk-test-xxxx.appspot.com",
      messagingSenderId: "012345678910",
      appId: "1:012345678:web:abcdef123456hijklm",
      measurementId: "G-ABC123DEF"
    };
  3. Save this information somewhere secure. You'll need it to connect to your Firebase app.

See Google's Firebase documentation for more information on the config object.

Use Firebase with Clerk in your code

Now that you have configured the integration, and you have retrieved your Firebase config object, it's time to use Firebase with Clerk in your code.

The following example:

  • Uses Clerk to generate an authentication token for Firebase's API.
  • Creates a button for signing into your Firebase app.
  • Creates a button for fetching example data from your Firestore database.

This example is written for Next.js App Router, but is supported by any React meta framework, such as Remix or Gatsby.

app/firebase/page.tsx
"use client";
import { useAuth } from "@clerk/nextjs";
import { initializeApp } from "firebase/app";
import { getAuth, signInWithCustomToken } from "firebase/auth";
import { getFirestore } from "firebase/firestore";
import { doc, getDoc } from "firebase/firestore";

const firebaseConfig = {
  apiKey: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
  authDomain: "clerk-example-xxxxx.firebaseapp.com",
  databaseURL: "https://clerk-example-xxxxx-default-xxxx.firebaseio.com",
  projectId: "clerk-test-xxxx",
  storageBucket: "clerk-test-xxxx.appspot.com",
  messagingSenderId: "012345678910",
  appId: "1:012345678:web:abcdef123456hijklm",
  measurementId: "G-ABC123DEF",
};

// Connect to your Firebase app
const app = initializeApp(firebaseConfig);
// Connect to your Firestore database
const db = getFirestore(app);
// Connect to Firebase auth
const auth = getAuth(app);

// Remove this if you do not have Firestore set up
// for your Firebase app
const getFirestoreData = async () => {
  const docRef = doc(db, "example", "example-document");
  const docSnap = await getDoc(docRef);
  if (docSnap.exists()) {
    console.log("Document data:", docSnap.data());
  } else {
    // docSnap.data() will be undefined in this case
    console.log("No such document!");
  }
};

export default function FirebaseUI() {
  const { getToken } = useAuth();
  const signInWithClerk = async () => {
    console.log("Sign in with clerk");
    const token = await getToken({ template: "integration_firebase" });
    const userCredentials = await signInWithCustomToken(auth, token || "");
     // The userCredentials.user object can call the methods of
     // the Firebase platform as an authenticated user.
    console.log("User:", userCredentials.user);
  };

  return (
    <main style={{ display: "flex", flexDirection: "column", rowGap: "1rem" }}>
      <button onClick={signInWithClerk}>Sign in</button>
      <button onClick={getFirestoreData}>Get document</button>
    </main>
  );
}

Use webhooks to sync Firebase data with Clerk

Learn how to sync Firebase auth or Firestore data with Clerk data using webhooks.

Create custom sign-up and sign-in pages in your Next.js app

Learn how add custom sign-up and sign-in pages with Clerk components in your Next.js application.

Deploy to Production

Learn how to deploy your Clerk app to production.

Deploy to Vercel

Learn how to deploy your Clerk app to production on Vercel.

Feedback

What did you think of this content?

Last updated on