All articles

Developers

Chrome Extension With Firebase Auth on Manifest V3

Quick answer: to use Firebase Authentication in a Manifest V3 Chrome extension, install Firebase from npm and bundle it (remote scripts are not allowed), import auth from firebase/auth/web-extension, and sign users in with chrome.identity plus signInWithCredential, or with email and password. signInWithPopup does not work directly in MV3 extension pages. For providers that need a popup, run it inside an offscreen document.

This guide gives a minimal working setup, based on what we learned building the Link App extension.

Why Firebase Auth is different under Manifest V3

Three MV3 rules shape everything.

  1. No remotely hosted code. All JavaScript must be inside the extension package. Loading the Firebase SDK from a CDN, or any flow that pulls in scripts from Google's servers, is rejected.
  2. Background pages are service workers. There is no DOM and no window, and the worker is shut down when idle. Global variables do not persist.
  3. Popup-based sign-in is restricted. signInWithPopup and signInWithRedirect load remote code, which breaks rule 1.

Chrome's Manifest V3 overview covers the platform changes.

Project structure

my-extension/
  src/
    background.js      # service worker
    popup.html
    popup.js
    firebase.js        # shared initialization
    offscreen.html     # only if you need popup providers
    offscreen.js
  public/
    manifest.json
  package.json
  vite.config.js       # or webpack / esbuild / rollup

Use any bundler. The requirement is that every Firebase module you import ends up inside your built files.

npm install firebase

manifest.json

{
  "manifest_version": 3,
  "name": "My Extension",
  "version": "1.0.0",
  "action": { "default_popup": "popup.html" },
  "background": { "service_worker": "background.js", "type": "module" },
  "permissions": ["identity", "storage"],
  "oauth2": {
    "client_id": "YOUR_CLIENT_ID.apps.googleusercontent.com",
    "scopes": ["openid", "email", "profile"]
  },
  "key": "YOUR_PUBLIC_KEY"
}
  • "type": "module" allows ES module imports in the service worker.
  • identity enables chrome.identity.
  • storage is for persisting state.
  • key fixes the extension ID during development, so the OAuth client keeps matching. Copy the public key from the Chrome Web Store developer dashboard, or generate one.

Initialize Firebase

// firebase.js
import { initializeApp } from 'firebase/app';
import { getAuth } from 'firebase/auth/web-extension';

const firebaseConfig = {
  apiKey: '...',
  authDomain: '...',
  projectId: '...',
  appId: '...',
};

export const app = initializeApp(firebaseConfig);
export const auth = getAuth(app);

The firebase/auth/web-extension entry point leaves out the code paths that MV3 forbids. Using plain firebase/auth is the most common reason for a Chrome Web Store rejection mentioning remotely hosted code.

A Firebase web API key identifies your project. It is not a secret. Protect your data with security rules, and restrict the key in Google Cloud Console.

Option 1: Google sign-in with chrome.identity

The simplest flow for Google accounts. Chrome obtains the OAuth token and you pass it to Firebase.

// auth.js
import { GoogleAuthProvider, signInWithCredential } from 'firebase/auth/web-extension';
import { auth } from './firebase.js';

export async function signInWithGoogle() {
  const { token } = await chrome.identity.getAuthToken({ interactive: true });
  const credential = GoogleAuthProvider.credential(null, token);
  return signInWithCredential(auth, credential);
}

export async function signOutEverywhere() {
  const { token } = await chrome.identity.getAuthToken({ interactive: false });
  if (token) await chrome.identity.removeCachedAuthToken({ token });
  await auth.signOut();
}

Google Cloud setup

  1. In Google Cloud Console, open APIs & Services > Credentials.
  2. Create an OAuth client ID of type Chrome Extension.
  3. Enter your extension's ID.
  4. Put the client ID in manifest.json under oauth2.
  5. In the Firebase console, enable Google under Authentication > Sign-in method.

Other Chromium browsers

getAuthToken depends on the browser's Google account integration and is not available in Edge, Brave or Opera. Use chrome.identity.launchWebAuthFlow there:

const redirectUri = chrome.identity.getRedirectURL();
const authUrl = new URL('https://accounts.google.com/o/oauth2/v2/auth');
authUrl.searchParams.set('client_id', WEB_CLIENT_ID);
authUrl.searchParams.set('response_type', 'id_token');
authUrl.searchParams.set('redirect_uri', redirectUri);
authUrl.searchParams.set('scope', 'openid email profile');
authUrl.searchParams.set('nonce', crypto.randomUUID());

const responseUrl = await chrome.identity.launchWebAuthFlow({
  url: authUrl.toString(),
  interactive: true,
});
const idToken = new URL(responseUrl.replace('#', '?')).searchParams.get('id_token');
const credential = GoogleAuthProvider.credential(idToken);
await signInWithCredential(auth, credential);

This uses a Web application OAuth client with the redirect URL https://<extension-id>.chromiumapp.org/ added as an authorized redirect URI.

Option 2: Email and password

These make direct API calls and work in the popup and the service worker with no extra setup.

import {
  signInWithEmailAndPassword,
  createUserWithEmailAndPassword,
} from 'firebase/auth/web-extension';
import { auth } from './firebase.js';

await signInWithEmailAndPassword(auth, email, password);

Email link sign-in and phone sign-in rely on reCAPTCHA or redirects and need the offscreen approach.

Option 3: Offscreen document for popup providers

For Apple, Microsoft, GitHub and other providers that require signInWithPopup, Firebase recommends an offscreen document containing an iframe hosted on your own website. The popup flow runs on the web page, where it is allowed, and the result is passed back.

1. Host a page on your site (for example on Firebase Hosting) that calls signInWithPopup and posts the result to its parent with postMessage.

2. Add the permission:

"permissions": ["offscreen"]

3. offscreen.html loads a script that embeds your hosted page in an iframe and relays messages.

4. In the service worker, create the document and request sign-in:

async function ensureOffscreen() {
  if (await chrome.offscreen.hasDocument()) return;
  await chrome.offscreen.createDocument({
    url: 'offscreen.html',
    reasons: ['DOM_SCRAPING'],
    justification: 'Firebase authentication popup',
  });
}

export async function signInWithProvider() {
  await ensureOffscreen();
  const result = await chrome.runtime.sendMessage({
    type: 'firebase-auth',
    target: 'offscreen',
  });
  await chrome.offscreen.closeDocument();
  return result;
}

The complete relay code is in Firebase's guide to authentication in Chrome extensions. Add your chrome-extension://<id> origin to Authorized domains in the Firebase console.

Sharing a session with your website

If users are already signed in on your web app, a second sign-in inside the extension is friction. A common pattern, and the one Link App uses with an extension-login page:

  1. The extension opens a page on your site.
  2. The user signs in there, or is already signed in.
  3. The page sends a token to the extension with chrome.runtime.sendMessage(extensionId, ...).
  4. The extension signs in with that token, for example using signInWithCustomToken with a token minted by your server.

Restrict which sites can message the extension:

"externally_connectable": {
  "matches": ["https://www.yoursite.com/*"]
}

Validate sender.origin in your onMessageExternal listener as well.

Service worker pitfalls

  • State disappears. The worker can stop after about 30 seconds of inactivity. Keep state in chrome.storage, not in variables.
  • Register listeners at the top level, synchronously. Listeners added inside async callbacks can be missed when the worker restarts.
  • Wait for auth to restore. After a restart, auth.currentUser is briefly null.
await auth.authStateReady();
const user = auth.currentUser;
  • Use chrome.alarms, not setInterval, for anything periodic.
  • Firestore listeners stop when the worker sleeps. Use one-off reads in the worker and keep realtime listeners in pages that stay open, such as a side panel.
  • Refresh tokens before API calls with user.getIdToken(), which renews automatically.

Common errors and fixes

Error Cause Fix
Web Store rejection: remotely hosted code Importing firebase/auth, or a CDN script Import from firebase/auth/web-extension and bundle everything
auth/operation-not-supported-in-this-environment Calling signInWithPopup in an extension page Use chrome.identity or an offscreen document
OAuth2 request failed: bad client id OAuth client type or extension ID mismatch Create a Chrome Extension client for the exact ID and set key in the manifest
auth/unauthorized-domain Extension origin not allowed Add chrome-extension://<id> to Firebase authorized domains
currentUser is null in the worker Auth not yet restored await auth.authStateReady()
Works in Chrome, fails in Edge or Brave getAuthToken unsupported Use launchWebAuthFlow
Refused to load the script Content Security Policy blocking remote code Remove remote scripts. MV3 does not permit relaxing this

Pre-publish checklist

  • Request only the permissions you use.
  • Search the build output for https:// script URLs. There should be none.
  • Test a cold start: reload the extension, wait for the worker to go idle, then act.
  • Test sign-out and switching accounts.
  • Test in each browser you support.
  • Write a clear justification for each permission in the store listing.

Frequently asked questions

Does Firebase Auth work with Manifest V3?

Yes, with the firebase/auth/web-extension entry point and an MV3-compatible sign-in method.

Why does signInWithPopup fail in a Chrome extension?

It loads remote code from Google, which MV3 blocks in extension pages. Use chrome.identity or an offscreen document.

Can I use Firestore in an MV3 extension?

Yes. Bundle it like any other module. Avoid long-lived listeners in the service worker.

How do I keep users signed in?

Firebase persists the session in extension storage. Wait for authStateReady() after the worker starts before reading currentUser.

Do I need the identity permission?

Only for chrome.identity flows. Email and password sign-in does not need it.

How do I get a stable extension ID during development?

Add the key field to the manifest with your extension's public key.

Is the Firebase API key safe to ship in an extension?

Yes. It identifies the project and is not a credential. Secure access with rules and key restrictions.

Can the same code run in Firefox?

Firefox supports MV3 with differences, such as background scripts instead of service workers in some versions. launchWebAuthFlow is available as browser.identity.launchWebAuthFlow.

Keep reading

Ready to never lose a link again?

Save links from any browser, app or social feed. Find every one of them in a second, on every device you own.