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

    Huzzah!

    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(
    firebaseConfig,
    "useAuth"
    );

    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
    this.firebase.auth().onAuthStateChanged(this.onAuthStateChanged);
    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 back on his Be An Expert bullshit avatarSwizec Teller back on his Be An Expert bullshit@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.dispatch("LOGIN");
    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,
    authResult
    });
    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.

    Cheers,
    ~Swizec

    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?
    Read more Software Engineering Lessons from Production

    I write articles with real insight into the career and skills of a modern software engineer. "Raw and honest from the heart!" as one reader described them. Fueled by lessons learned over 20 years of building production code for side-projects, small businesses, and hyper growth startups. Both successful and not.

    Subscribe below ๐Ÿ‘‡

    Software Engineering Lessons from Production

    Join Swizec's Newsletter and get insightful emails ๐Ÿ’Œ 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 15,883+ engineers learning lessons from my "raw and honest from the heart" emails.

    โญ๏ธโญ๏ธโญ๏ธโญ๏ธโœจ
    4.5 stars average rating

    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

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

    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 โค๏ธ