Firebase login with Google in plain javascript

Getting a JWT is easy peasy

Example usage (open code here)

The code

  1. Defines specifically what three minimum parameters you need, the project ID, API key and auth domain
  2. It hooks up the events required for login and logout so that you can control your UI changes based on it
  3. It wraps login and logout functions into a single simple function call
  4. As long as you initialise this on page load, any previous login will automatically re-login and refresh the token

How it works

function initFirebaseAuth(config) {
if (!config.projectId) throw Error('Missing projectId');
if (!config.apiKey) throw Error('Missing apiKey');
if (!config.authDomain) throw Error('Missing authDomain');
const firebaseConfig = {
apiKey: config.apiKey,
projectId: config.projectId,
authDomain: config.authDomain
firebase.auth().onAuthStateChanged(async function(user) {
if (!user && config.loggedOut) {
if (!config.loggedIn) return;
const token = await user.getIdToken();
config.loggedIn(user, token);
function handleAuthError(error, onError) {
if (error.code === "auth/unauthorized-domain") {
const authDomain = firebase.auth().app.options.authDomain;
const projectName = authDomain.replace('', '');
onError(new Error(`Looks like your domain isn't valid for this project. Please check your Firebase Auth domain configuration.${projectName}/authentication/providers`));
} else {

Trying it out

The example app interface, asking for firebase settings before logging in

Any questions on that?



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
David Dikman

David Dikman


Full-stack developer and founder. Writing here and at Currently open for contract work.