Swizec Teller - a geek with a hatswizec.com

Senior Mindset Book

Get promoted, earn a bigger salary, work for top companies

Senior Engineer Mindset cover
Learn more

    [CodeWithSwiz 20] Adding Firebase support to useAuth, pt2

    Firebase continues to be ๐Ÿ’ฉ. No wonder people keep asking for support in useAuth.

    CodeWithSwiz is a weekly live show. Like a podcast with video and fun hacking. Focused on experiments and open source. Join live Mondays

    Good progress this week! We got a Firebase UI login dialog to show up ๐Ÿฅณ

    FirebaseUI login and signup widget

    To be honest, I was expecting more from a module that adds 64kB[^1] of JavaScript. Guess styles come separately?

    Where we at

    Signup flow ends with an error. Return false from a callback or provide a URL. Documentation mentions both the URL and the callback somewhat off-hand. Hard to find.

    An issue from 2016 mentions the URL is required. 5 years later documentation and error message say it isn't. ๐Ÿฅฒ

    signInSuccessWithAuthResult: function(authResult, redirectUrl) {
      // User successfully signed in.
      // Return type determines whether we continue the redirect automatically
      // or whether we leave that to developer to handle.
      return true;

    We do get an earlier error about our callback config. ๐Ÿค”

    On the bright side, a user shows up in Firebase. That means login works and useAuth isn't resolving it correctly.

    User created in Firebase
    User created in Firebase


    How we got here

    In part 1 of Firebase Auth we sketched out a new provider for useAuth. Configured imports, initialized FirebaseUI, set up the provider class.

    This episode we:

    1. Improved imports
    2. Figured out how to initialize Firebase
    3. Discovered the onAuthStateChange observer
    4. Got frustrated at Google's SEO where any error message you google points to Firebase docs that do not mention that error message
    5. Fiddled with TypeScript types
    6. Fired off the login flow

    Improved imports

    Here's the correct way to import Firebase and the Auth UI.

    import { auth as FirebaseAuthUI } from "firebaseui";
    import Firebase from "firebase/app";
    import "firebase/auth";

    Firebase is a library from the before times and likes to modify globals. In the name of "making it easy".

    You import firebase/auth into nothing. Refer to it through the Firebase object.

    Just like we used to do in 2010 when "JavaScript Bundler" meant "Joe with a pickaxe crafting a giant file with <script> tags in exactly the right sequence"

    Correctly initialize Firebase

    We found the incantantion to init Firebase. You must create an app. A project is not enough.

    Then you click the app and find a firebaseConfig object.

    Firebase Config
    Firebase Config

    Don't worry about stealing those secrets, they're for the demo app. I intend to share them with the quick start guide.

    Use them in the auth provider constructor:

    // src/providers/FirebaseUI.ts
    export class FirebaseUI implements AuthProviderClass {
    	// ..
    	constructor(params: AuthOptions & FirebaseOptions) {
    		// ..
    		this.firebase = Firebase.initializeApp(

    Obvious in retrospect. Surprisingly hard to find.

    The 2nd argument โ€“ย "useAuth" โ€“ tells Firebase to initialize this as a separate app. Avoid overwriting any global Firebase config you might have.

    Final API will have to let you choose. ๐Ÿค”

    onAuthStateChange observer

    onAuthStateChange was a great find! Lets you hook into the authentication flow and update your state machine.

    // src/providers/FirebaseUI.ts
    private onAuthStateChanged(user: Firebase.User) {
        console.log("HAI", user);

    Start in exploration mode ๐Ÿ‘‰ print current user when state changes. First you get a null, then you go through the signup flow and get ... something.

    Minified private TypeScript fields, I'm told. You call .toJSON() to get the real value.

    Reload the page after signup and callback prints this again. Login works ๐Ÿค˜

    We'll use it next time to update useAuth's understanding of current user.

    Fire off the login flow

    To fire off the login flow you need to pass all the config. Bit weird but sure.

    public authorize() {
        // Open login dialog
        this.ui.start("#firebaseui-auth-container", {
            signInOptions: this.signInOptions,
            signInFlow: "popup",
            signInSuccessWithAuthResult: function(
                authResult: any,
                redirectUrl: string
            ) {
                console.log({ authResult, redirectUrl });
                this.dispatch("AUTHENTICATED", {
                    user: this.firebase.auth().currentUser,
                return false;

    useAuth calls this method when user clicks the login button. We put XState into the logging-in state with dispatch('LOGIN') then fire up the UI.

    Full options listed here, if you scroll down.

    On success, we print the auth result and current user. Tell useAuth and it handles the UI. Redirecting back to destination or at least re-render.

    But it never gets there ๐Ÿค”

    Thank you

    Aaaaand I figured out what's wrong! You have to wrap signInSuccessWithAuthResult in a callbacks:{} object. Because of course you do.

    ๐ŸŽ‰ it works

    You're a great rubber ducky my friend.


    [^1] size difference measured by removing imports, deploying to Vercel, and looking at network tab.

    Published on January 19th, 2021 in CodeWithSwiz, Technical, Firebase, useAuth, Livecoding

    Did you enjoy this article?

    Continue reading about [CodeWithSwiz 20] Adding Firebase support to useAuth, pt2

    Semantically similar articles hand-picked by GPT-4

    Senior Mindset Book

    Get promoted, earn a bigger salary, work for top companies

    Learn more

    Have a burning question that you think I can answer? Hit me up on twitter and I'll do my best.

    Who am I and who do I help? I'm Swizec Teller and I turn coders into engineers with "Raw and honest from the heart!" writing. No bullshit. Real insights into the career and skills of a modern software engineer.

    Want to become a true senior engineer? Take ownership, have autonomy, and be a force multiplier on your team. The Senior Engineer Mindset ebook can help ๐Ÿ‘‰ swizec.com/senior-mindset. These are the shifts in mindset that unlocked my career.

    Curious about Serverless and the modern backend? Check out Serverless Handbook, for frontend engineers ๐Ÿ‘‰ ServerlessHandbook.dev

    Want to Stop copy pasting D3 examples and create data visualizations of your own? Learn how to build scalable dataviz React components your whole team can understand with React for Data Visualization

    Want to get my best emails on JavaScript, React, Serverless, Fullstack Web, or Indie Hacking? Check out swizec.com/collections

    Did someone amazing share this letter with you? Wonderful! You can sign up for my weekly letters for software engineers on their path to greatness, here: swizec.com/blog

    Want to brush up on your modern JavaScript syntax? Check out my interactive cheatsheet: es6cheatsheet.com

    By the way, just in case no one has told you it yet today: I love and appreciate you for who you are โค๏ธ

    Created by Swizec with โค๏ธ