Firebase continues to be π©. No wonder people keep asking for support in useAuth.
If you do, Iβll switch to useAuth @nozzleio
β Tanner Linsley βοΈ (@tannerlinsley) January 12, 2021
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 π₯³

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.
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:
- Improved imports
- Figured out how to initialize Firebase
- Discovered the
onAuthStateChangeobserver - Got frustrated at Google's SEO where any error message you google points to Firebase docs that do not mention that error message
- Fiddled with TypeScript types
- 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.
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.tsexport 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.tsthis.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.
Wow when Firebase returns the authenticated user in a callback ... I guess *some* of those are user properties π€¨ pic.twitter.com/0jtGUgjrGI
β Swizec Teller published ServerlessHandbook.dev (@Swizec) January 19, 2021
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 dialogthis.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.

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.
Learned something new?
Want to become a high value JavaScript expert?
Here's how it works π
Leave your email and I'll send you an Interactive Modern JavaScript Cheatsheet πright away. After that you'll get thoughtfully written emails every week about React, JavaScript, and your career. Lessons learned over my 20 years in the industry working with companies ranging from tiny startups to Fortune5 behemoths.
Start with an interactive cheatsheet π
Then get thoughtful letters π on mindsets, tactics, and technical skills for your career.
"Man, love your simple writing! Yours is the only email I open from marketers 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. π"
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Β β€οΈ