react-firebaseui

repository·master·Indexed 23 days ago

https://github.com/firebase/firebaseui-web-react

A React wrapper for the firebaseui Javascript library, providing customizable UI components for the Firebase SDK. It specifically offers a drop-in authentication UI for Firebase Auth via two primary components: StyledFirebaseAuth, which includes bundled CSS, and FirebaseAuth, which is optimized for smaller bundle sizes when using CSS loaders like Webpack. Version 6.0.0.

Tokens
3.1K
Snippets
7
Records
12
Agent score
30%

What's inside react-firebaseui

  1. Compare FirebaseAuth and StyledFirebaseAuth

    master

    There are two primary components for adding FirebaseUI auth to your application:

    • StyledFirebaseAuth: The simplest option. It comes bundled with the necessary CSS directly, so no special configuration is needed for packaging.
    • FirebaseAuth: Better for performance and smaller bundle sizes if you are using a CSS/style loader (like Webpack) as part of your build configuration. It requires you to handle the CSS manually.
  2. Configure Webpack for FirebaseAuth (CSS Loaders)

    master

    If you use the FirebaseAuth component (which requires manual CSS handling), ensure your Webpack configuration includes style-loader and css-loader. Crucially, do not exclude node_modules from this rule, as the library's CSS is located there.

    {
      module: {
        rules: [
          {
            test: /\.css/,
            use: [ 'style-loader', 'css-loader' ]
          }
        ]
      }
    }
  3. Configure Webpack with ExtractTextPlugin and CSS Modules

    master

    If your project uses CSS modules, you must handle files in node_modules separately so they are treated as global CSS rather than modules. Use an include rule for node_modules and a exclude rule for your project's module files.

    {
      plugins: [new ExtractTextPlugin('./bundle.css')],
      module: {
        rules: [
          // CSS loaders for CSS modules in your project. We exclude CSS files in ./node_modules
          {
            test: /\.css$/,
            exclude: [/\.global\./, /node_modules/],
            loader: ExtractTextPlugin.extract(
              {
                fallback: 'style-loader',
                use:[
                  {
                    loader: 'css-loader',
                    options: {
                      importLoaders: 1,
                      modules: true,
                      autoprefixer: true,
                      minimize: true,
                      localIdentName: '[name]__[local]___[hash:base64:5]'
                    }
                  }
                ]
              })
          },
    
          // CSS loaders for global CSS files which includes files in ./node_modules
          {
            test: /\.css/,
            include: [/\.global\./, /node_modules/],
            loader: ExtractTextPlugin.extract(
              {
                fallback: 'style-loader',
                use: ['css-loader']
              })
          }
        ]
      }
    }
  4. Set up the Firebase UI React example app

    master

    To run the sample application provided in this repository, follow these steps to configure your Firebase project and build the local environment:

    1. Configure Firebase Console:

      • Create a project in the Firebase console.
      • Navigate to the Authentication section.
      • Open the Sign-In Method tab.
      • Enable Google and Email/Password sign-in providers.
    2. Install Dependencies:

      • Install project dependencies: npm install
      • Install the Firebase CLI globally: npm install -g firebase-tools
    3. Local Environment Setup:

      • Link your local environment to your Firebase project: firebase use --add
      • Build the application: npm run build
      • Start the local server: npm run serve
    4. Access the App:

    npm install
    npm install -g firebase-tools
    firebase use --add
    npm run build
    npm run serve
  5. Configure Webpack with ExtractTextPlugin

    master

    To extract CSS into a separate file using ExtractTextPlugin, use the following configuration. Ensure your rule does not exclude node_modules.

    {
      plugins: [new ExtractTextPlugin('./bundle.css')],
      module: {
        rules: [
          {
            test: /\.css/,
            loader: ExtractTextPlugin.extract(
              {
                fallback: 'style-loader',
                use: ['css-loader']
              })
          }
        ]
      }
    }
  6. Style the FirebaseUI widget

    master

    To override the default styling of the FirebaseAuth or StyledFirebaseAuth widget, import a custom CSS file globally in your application.

    If you are using the Webpack configuration for CSS modules (with ExtractTextPlugin), naming your file with a .global.css suffix (e.g., firebaseui-styling.global.css) will ensure it is treated as global CSS and not processed by the CSS modules loader.

    import './firebaseui-styling.global.css'; // Import globally. Not with CSS modules.
  7. Server-Side Rendering (SSR) limitations

    master
    FirebaseUI React cannot be rendered on the server because the underlying firebaseui library requires a browser environment. While you can import the library in an SSR application without causing errors, no elements will be rendered on the server.
  8. Use StyledFirebaseAuth with local state

    master

    To manage authentication state locally within your React component instead of using a redirect, set signInSuccessWithAuthResult to return false in the callbacks object of your uiConfig. You can then use firebase.auth().onAuthStateChanged to update your local state.

    // Import FirebaseAuth and firebase.
    import React, { useEffect, useState } from 'react';
    import StyledFirebaseAuth from 'react-firebaseui/StyledFirebaseAuth';
    import firebase from 'firebase/compat/app';
    import 'firebase/compat/auth';
    
    // Configure Firebase.
    const config = {
      apiKey: 'AIzaSyAeue-AsYu76MMQlTOM-KlbYBlusW9c1FM',
      authDomain: 'myproject-1234.firebaseapp.com',
      // ...
    };
    firebase.initializeApp(config);
    
    // Configure FirebaseUI.
    const uiConfig = {
      // Popup signin flow rather than redirect flow.
      signInFlow: 'popup',
      // Redirect to /signedIn after sign in is successful. Alternatively you can provide a callbacks.signInSuccess function.
      signInOptions: [
        firebase.auth.GoogleAuthProvider.PROVIDER_ID,
        firebase.auth.FacebookAuthProvider.PROVIDER_ID
      ],
      callbacks: {
        // Avoid redirects after sign-in.
        signInSuccessWithAuthResult: () => false,
      },
    };
    
    function SignInScreen() {
      const [isSignedIn, setIsSignedIn] = useState(false); // Local signed-in state.
    
      // Listen to the Firebase Auth state and set the local state.
      useEffect(() => {
        const unregisterAuthObserver = firebase.auth().onAuthStateChanged(user => {
          setIsSignedIn(!!user);
        });
        return () => unregisterAuthObserver(); // Make sure to un-register Firebase observers when the component unmounts.
      }, []);
    
      if (!isSignedIn) {
        return (
          <div>
            <h1>My App</h1>
            <p>Please sign-in:</p>
            <StyledFirebaseAuth uiConfig={uiConfig} firebaseAuth={firebase.auth()} />
          </div>
        );
      }
      return (
        <div>
          <h1>My App</h1>
          <p>Welcome {firebase.auth().currentUser.displayName}! You are now signed-in!</p>
          <a onClick={() => firebase.auth().signOut()}>Sign-out</a>
        </div>
      );
    }
    
    export default SignInScreen;
  9. Use StyledFirebaseAuth with a redirect

    master

    To implement a sign-in flow that redirects the user to a specific URL upon successful authentication, use the signInSuccessUrl property in your uiConfig object.

    // Import FirebaseAuth and firebase.
    import React from 'react';
    import StyledFirebaseAuth from 'react-firebaseui/StyledFirebaseAuth';
    import firebase from 'firebase/compat/app';
    import 'firebase/compat/auth';
    
    // Configure Firebase.
    const config = {
      apiKey: 'AIzaSyAeue-AsYu76MMQlTOM-KlbYBlusW9c1FM',
      authDomain: 'myproject-1234.firebaseapp.com',
      // ...
    };
    firebase.initializeApp(config);
    
    // Configure FirebaseUI.
    const uiConfig = {
      // Popup signin flow rather than redirect flow.
      signInFlow: 'popup',
      // Redirect to /signedIn after sign in is successful. Alternatively you can provide a callbacks.signInSuccess function.
      signInSuccessUrl: '/signedIn',
      // We will display Google and Facebook as auth providers.
      signInOptions: [
        firebase.auth.GoogleAuthProvider.PROVIDER_ID,
        firebase.auth.FacebookAuthProvider.PROVIDER_ID,
      ],
    };
    
    function SignInScreen() {
      return (
        <div>
          <h1>My App</h1>
          <p>Please sign-in:</p>
          <StyledFirebaseAuth uiConfig={uiConfig} firebaseAuth={firebase.auth()} />
        </div>
      );
    }
    
    export default SignInScreen;
  10. Access the FirebaseUI instance via uiCallback

    master

    You can access the underlying FirebaseUI instance before it starts by passing a uiCallback function to the component. This allows you to call methods on the instance, such as ui.disableAutoSignIn().

    <StyledFirebaseAuth 
      uiCallback={ui => ui.disableAutoSignIn()} 
      uiConfig={uiConfig} 
      firebaseAuth={firebase.auth()} 
    />
    // ...
    
    return (
      <div>
        <h1>My App</h1>
        <p>Please sign-in:</p>
        <StyledFirebaseAuth uiCallback={ui => ui.disableAutoSignIn()} uiConfig={uiConfig} firebaseAuth={firebase.auth()}/>
      </div>
    );
  11. Import FirebaseAuth and StyledFirebaseAuth

    master

    The react-firebaseui package exports two primary components for integrating Firebase Authentication UI into a React application:

    1. FirebaseAuth: The base component for FirebaseUI.
    2. StyledFirebaseAuth: A pre-styled version of the FirebaseUI component.

    You can import them from the package root.