{"id":20974238,"url":"https://github.com/thirdweb-example/firebase-auth","last_synced_at":"2025-05-14T12:31:17.913Z","repository":{"id":107808174,"uuid":"534485145","full_name":"thirdweb-example/firebase-auth","owner":"thirdweb-example","description":"Integrate sign in with Ethereum using thirdweb Auth into your Firebase application","archived":true,"fork":false,"pushed_at":"2024-04-12T00:25:40.000Z","size":297,"stargazers_count":19,"open_issues_count":0,"forks_count":9,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-03-24T12:15:14.834Z","etag":null,"topics":["auth","firebase","web2"],"latest_commit_sha":null,"homepage":"https://firebase-auth.thirdweb-example.com/","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/thirdweb-example.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE.md","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2022-09-09T03:34:01.000Z","updated_at":"2024-09-09T21:50:12.000Z","dependencies_parsed_at":"2024-04-18T20:32:52.575Z","dependency_job_id":null,"html_url":"https://github.com/thirdweb-example/firebase-auth","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/thirdweb-example%2Ffirebase-auth","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/thirdweb-example%2Ffirebase-auth/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/thirdweb-example%2Ffirebase-auth/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/thirdweb-example%2Ffirebase-auth/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/thirdweb-example","download_url":"https://codeload.github.com/thirdweb-example/firebase-auth/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254142283,"owners_count":22021495,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["auth","firebase","web2"],"created_at":"2024-11-19T04:27:31.185Z","updated_at":"2025-05-14T12:31:17.555Z","avatar_url":"https://github.com/thirdweb-example.png","language":"TypeScript","readme":"\u003e [!Important]  \n\u003e This repository is referencing the `mumbai` chain.\n\u003e \n\u003e `Mumbai` [is deprecated since 08/04/2024](https://blog.thirdweb.com/deprecation-of-mumbai-testnet/), meaning the code in this repository will no longer work out of the box.\n\u003e\n\u003e You can still use this repository, however you will have to switch any references to `mumbai` to another chain.\n\n# thirdweb Auth + Firebase\n\nThis template shows you can use thirdweb Auth as a custom authentication provider for Firebase, and automatically create a document in the `users` Firestore collection when a user signs up successfully.\n\n\u003cdiv className=\"row\" style={{ marginTop: 24 }}\u003e\n  \u003cdiv className=\"col col--12\"\u003e\n    \u003cQuickstartCard\n      name=\"Example Repo: Firebase Integration\"\n      link=\"https://github.com/thirdweb-example/firebase-auth\"\n      description=\"Implement thirdweb Auth with Firebase\"\n      image=\"/assets/languages/firebase.png\"\n    /\u003e\n  \u003c/div\u003e\n\u003c/div\u003e\n\n## Pre-requisites\n\n- [Create a Firebase project](https://firebase.google.com/docs/web/setup#create-project)\n- [Register your Firebase app](https://firebase.google.com/docs/web/setup#register-app)\n- [Create and export a service account as a JSON file](https://firebase.google.com/docs/admin/setup#initialize-sdk)\n- Make sure to enable Firebase Authentication as we'll be using the [Custom Authentication](https://firebase.google.com/docs/auth/web/custom-auth?hl=en\u0026authuser=0) method and create a [Cloud Firestore](https://firebase.google.com/docs/firestore/quickstart?hl=en\u0026authuser=0) database within your project.\n\n## Set Up\n\nTo begin with, let's create a new Next.js project with the SDK configured:\n\n```bash\nnpx thirdweb create app --next --ts\n```\n\nFrom within the created directory, we need to install `@thirdweb-dev/auth`, `firebase` and `firebase-admin`:\n\n```bash npm2yarn\nnpm install @thirdweb-dev/auth firebase firebase-admin\n```\n\n### Configure Firebase\n\nWe'll use environment variables to store our Firebase configuration.\n\nCreate a `.env.local` file in the root of your project and add the corresponding values from your Firebase project:\n\n```\nNEXT_PUBLIC_API_KEY=\u003cfirebase-app-api-key\u003e\nNEXT_PUBLIC_AUTH_DOMAIN=\u003cfirebase-app-auth-domain\u003e\nNEXT_PUBLIC_PROJECT_ID=\u003cfirebase-app-project-id\u003e\nNEXT_PUBLIC_STORAGE_BUCKET=\u003cfirebase-app-storage-bucket\u003e\nNEXT_PUBLIC_MESSAGING_SENDER_ID=\u003cfirebase-app-messaging-sender-id\u003e\nNEXT_PUBLIC_APP_ID=\u003cfirebase-app-app-id\u003e\nFIREBASE_PRIVATE_KEY=\u003cservice-account-private-key\u003e\nFIREBASE_CLIENT_ID=\u003cservice-account-client-id\u003e\nFIREBASE_PRIVATE_KEY_ID=\u003cservice-account-private-key-id\u003e\nFIREBASE_CLIENT_EMAIL=\u003cservice-account-client-email\u003e\n```\n\nMost of the above environment variables can be found in the settings page of your Firebase project (after adding a Web app to your project), or in the service role JSON file you created and downloaded earlier.\n\nCreate a new directory called `lib` and create two helper scripts to initialize Firebase in the browser and server:\n\n- [lib/initFirebase.ts](https://github.com/thirdweb-example/firebase-auth/blob/main/lib/initFirebase.ts)\n- [lib/initFirebaseAdmin.ts](https://github.com/thirdweb-example/firebase-auth/blob/main/lib/initFirebaseAdmin.ts)\n\nNow we have an easy way to access Firebase Auth and Firestore in both client and server environments!\n\n### Configure thirdweb Auth\n\nFinally, to configure thirdweb Auth, we just need to add the `NEXT_PUBLIC_THIRDWEB_AUTH_DOMAIN` evironment variable to the `.env.local` file as follows:\n\n```\nNEXT_PUBLIC_THIRDWEB_AUTH_DOMAIN=\u003cthirdweb-auth-domain\u003e\n```\n\nThe `NEXT_PUBLIC_THIRDWEB_AUTH_DOMAIN` is used to prevent phishing attacks - and is usually set to the domain of your project like `example.com`. You can read more about it in the [thirdweb Auth Documentation](https://portal.thirdweb.com/auth/how-auth-works/sign-in-with-wallet#domain).\n\n### ThirdwebProvider\n\nInside the `pages/_app.tsx` file, configure the `authConfig` option:\n\n```ts title=\"pages/_app.tsx\"\nimport type { AppProps } from \"next/app\";\nimport { ThirdwebProvider } from \"@thirdweb-dev/react\";\n\n// This is the chain your dApp will work on.\nconst activeChain = \"mumbai\";\n\nfunction MyApp({ Component, pageProps }: AppProps) {\n  return (\n    \u003cThirdwebProvider\n      authConfig={{\n        domain: process.env.NEXT_PUBLIC_THIRDWEB_AUTH_DOMAIN as string,\n      }}\n      activeChain={activeChain}\n    \u003e\n      \u003cComponent {...pageProps} /\u003e\n    \u003c/ThirdwebProvider\u003e\n  );\n}\n\nexport default MyApp;\n```\n\n## Sign Up / Log In Users\n\nThe process of creating users in Firebase by authenticating them with their wallet has two steps:\n\n1. Authenticate the user with their wallet\n2. Create a user in Firebase with the knowledge that they own this wallet\n\nOn the homepage (`pages/index.tsx`), we'll allow the user to connect their wallet and then sign in with Ethereum.\n\n```tsx title=\"pages/index.tsx\"\nimport React from \"react\";\nimport { ConnectWallet, useAddress, useAuth } from \"@thirdweb-dev/react\";\nimport { doc, serverTimestamp, setDoc } from \"firebase/firestore\";\nimport { signInWithCustomToken } from \"firebase/auth\";\nimport initializeFirebaseClient from \"../lib/initFirebase\";\n\nexport default function Login() {\n  const thirdwebAuth = useAuth();\n  const address = useAddress();\n  const { auth, db } = initializeFirebaseClient();\n\n  return (\n    \u003cdiv\u003e\n      {address ? (\n        \u003cbutton onClick={() =\u003e signIn()}\u003eSign in with Wallet\u003c/button\u003e\n      ) : (\n        \u003cConnectWallet /\u003e\n      )}\n    \u003c/div\u003e\n  );\n}\n```\n\nThe `signIn` function:\n\n1. Makes a request to the `api/auth/login` endpoint to get a custom token from Firebase\n2. Signs the user in with the custom token\n3. Creates a user in Firestore with the verified user's address\n\n```tsx title=\"pages/index.tsx\"\n// Note: This function lives inside the Login component above.\nconst signIn = async () =\u003e {\n  // Use the same address as the one specified in _app.tsx.\n  const payload = await thirdwebAuth?.login();\n\n  try {\n    // Make a request to the API with the payload.\n    const res = await fetch(\"/api/auth/login\", {\n      method: \"POST\",\n      headers: {\n        \"Content-Type\": \"application/json\",\n      },\n      body: JSON.stringify({ payload }),\n    });\n\n    // Get the returned JWT token to use it to sign in with\n    const { token } = await res.json();\n\n    // Sign in with the token.\n    const userCredential = await signInWithCustomToken(auth, token);\n    // On success, we have access to the user object.\n    const user = userCredential.user;\n\n    // If this is a new user, we create a new document in the database.\n    const usersRef = doc(db, \"users\", user.uid!);\n    const userDoc = await getDoc(usersRef);\n\n    if (!userDoc.exists()) {\n      // User now has permission to update their own document outlined in the Firestore rules.\n      setDoc(usersRef, { createdAt: serverTimestamp() }, { merge: true });\n    }\n  } catch (error) {\n    console.error(error);\n  }\n};\n```\n\nIn this function, you'll notice we're calling the `/api/auth/login` endpoint to get a\n[custom JWT token from Firebase](https://firebase.google.com/docs/auth/admin/create-custom-tokens#create_custom_tokens_using_the_firebase_admin_sdk).\n\nLet's take a look at that API route.\n\n### Auth API Route\n\nCreate a folder that lives in the `/pages/api/auth` directory called `login.ts`.\n\nThis API route is responsible for:\n\n1. Verifying the payload provided by the client\n2. Once the payload is verified, creating a [custom token](https://firebase.google.com/docs/auth/admin/create-custom-tokens#create_custom_tokens_using_the_firebase_admin_sdk)\n   for the user to sign in to Firebase with.\n\n```ts title=\"pages/api/auth/login.ts\"\nimport { NextApiRequest, NextApiResponse } from \"next\";\nimport { verifyLogin } from \"@thirdweb-dev/auth/evm\";\nimport initializeFirebaseServer from \"../../../lib/initFirebaseAdmin\";\n\nconst login = async (req: NextApiRequest, res: NextApiResponse) =\u003e {\n  // Grab the login payload the user sent us with their request.\n  const payload = req.body.payload;\n\n  const { address, error } = await verifyLogin(\n    process.env.NEXT_PUBLIC_THIRDWEB_AUTH_DOMAIN as string,\n    payload\n  );\n  if (!address) {\n    return res.status(401).json({ error });\n  }\n\n  // Initialize the Firebase Admin SDK.\n  const { auth } = initializeFirebaseServer();\n\n  // Generate a JWT token for the user to be used on the client-side.\n  const token = await auth.createCustomToken(address);\n\n  // Send the token to the client-side.\n  return res.status(200).json({ token });\n};\n\nexport default login;\n```\n\nYou'll now be able to use Firebase Authentication to authenticate users with their wallets!\n\n### Firestore Rules (Optional)\n\nYou'll likely want to add a [security rule](https://firebase.google.com/docs/firestore/security/get-started)\nto your Firestore database that only allows users to update their documents.\n\n```cel title=\"firestore.rules\"\nrules_version = '2';\nservice cloud.firestore {\n  match /databases/{database}/documents {\n    // The wildcard expression {userId} makes the userId variable available in rules.\n    match /users/{userId} {\n      // Only allow users to update their own documents.\n      allow create, update, delete: if request.auth != null \u0026\u0026 request.auth.uid == userId;\n      // But anybody can read their profile.\n      allow read;\n    }\n  }\n}\n```\n\n### Viewing the Result\n\nWhen you click the \"Sign in with Ethereum\" button and successfully sign in, you'll be signed up as a user in Firebase and a new document will be created in your `users` collection in Firestore:\n\nYou can now use all the functionality of Firebase Authentication and Firestore to build your app!\n\n## What's Next?\n\n- [Get the current Firebase user](https://github.com/thirdweb-example/firebase-auth/blob/main/lib/useFirebaseUser.ts)\n- [Read the current user's document from Firestore](https://github.com/thirdweb-example/firebase-auth/blob/main/lib/useFirebaseUserDocument.ts)\n- [Sign out](https://github.com/thirdweb-example/firebase-auth/blob/main/pages/index.tsx#L84-L89)\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fthirdweb-example%2Ffirebase-auth","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fthirdweb-example%2Ffirebase-auth","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fthirdweb-example%2Ffirebase-auth/lists"}