Swizec Teller - a geek with a hatswizec.com

    [CodeWithSwiz 20] Adding Firebase support to useAuth, pt2

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

    Tanner Linsley avatarTanner Linsley@tannerlinsley
    @Swizec If you do, I’ll switch to useAuth @nozzleio

    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 64kB1 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.

    Swizec Teller published ServerlessHandbook.dev avatarSwizec Teller published ServerlessHandbook.dev@Swizec
    Wow when Firebase returns the authenticated user in a callback ... I guess *some* of those are user properties 🀨
    Tweet media

    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.

    Did you enjoy this article?

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

    Learned something new?
    Want to become an expert?

    Here's how it works πŸ‘‡

    Leave your email and I'll send you thoughtfully written emails every week about React, JavaScript, and your career. Lessons learned over 20 years in the industry working with companies ranging from tiny startups to Fortune5 behemoths.

    Join Swizec's Newsletter

    And get thoughtful letters πŸ’Œ on mindsets, tactics, and technical skills for your career. Real lessons from building production software. No bullshit.

    "Man, love your simple writing! Yours is the only newsletter I open and only blog that I give a fuck to read & scroll till the end. And wow always take away lessons with me. Inspiring! And very relatable. πŸ‘Œ"

    ~ Ashish Kumar

    Join over 14,000 engineers just like you already improving their careers with my letters, workshops, courses, and talks. ✌️

    Have a burning question that you think I can answer?Β I don't have all of the answers, but I have some! Hit me up on twitter or book a 30min ama for in-depth help.

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

    Curious about Serverless and the modern backend? Check out Serverless Handbook, modern backend for the frontend engineer.

    Ready to learn how it all fits together and build a modern webapp from scratch? Learn how to launch a webapp and make your first πŸ’° on the side with ServerlessReact.Dev

    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 ❀️