Remix Firebase Google Auth
Tags: react, javascript, remix, webdev
Published: 2022-02-27 23:20:44

Authentication is a very important part of any app. In this tutorial we are going to integrate Firebase Google Authentication in a  Remix app.
[Example](https://blog.hosenur.dev)
Users when authenticated can like posts, post comments under posts.

## Setting Up Our Project 🚀

### Create a new Remix project

Create a new Remix project by running the following command on your terminal:

```js
npx create-remix@latest
```

Choose your preferred Hosting Platform, Language and navigate to the projects directory.
Install required packages

```js
npm install firebase
```

## Configuring Firebase in our project 🔥

### Connect Firebase

Create a new firebase project in the firebase console, or use an existing one, and follow the steps below.

- Provide App Nickname.
- Click on Register app.
- You will be provided with the Add Firebase SDK screen.
- Copy the **firebaseConfig** object variable.
- Create a folder names **contexts** inside the app folder.
- Create a new **firebase.js** file in the contexts folder and copy and paste the snippet given below and replace your **firebaseConfig**.

```js
// firebase.js
import { initializeApp } from "firebase/app";
import { getAuth } from "firebase/auth";
import { getFirestore } from "firebase/firestore";

const firebaseConfig = {
  apiKey: "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  authDomain: "XXXXXXXXXXXXXXX.firebaseapp.com",
  projectId: "XXXXXXXXXXXXXXX",
  storageBucket: "XXXXXXXXXXXXXXX.appspot.com",
  messagingSenderId: "XXXXXXXXXXX",
  appId: "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
};

const app = initializeApp(firebaseConfig);
export const auth = getAuth(app);
export const db = getFirestore(app);
```

- Return to the Firebase console and click on Authentication, then click on Sign-in Method and enable Google under Additional Providers tab and click on Save. If you have a custom domain , you can add that in the authorized domains section.

### Creating the AuthProvider

Create a **AuthContext.js** file in the **contexts** folder and paste the following code snippet.

```js
import React, { useContext, useState, useEffect } from "react";
import { auth } from "./firebase";
import { signInWithPopup, GoogleAuthProvider } from "firebase/auth";

const AuthContext = React.createContext();

export function useAuth() {
  return useContext(AuthContext);
}

export function AuthProvider({ children }) {
  const [currentUser, setCurrentUser] = useState();
  const [loading, setLoading] = useState(true);

  const signInWithGoogle = () => {
    const provider = new GoogleAuthProvider();
    signInWithPopup(auth, provider)
      .then((res) => {
        setCurrentUser(res.user);
      })
      .catch((err) => {
        console.log(err);
      });
  };

  useEffect(() => {
    const unsubscribe = auth.onAuthStateChanged((user) => {
      setCurrentUser(user);
      setLoading(false);
    });
    return unsubscribe;
  }, []);

  const value = {
    signInWithGoogle,
    currentUser,
  };

  return (
    <AuthContext.Provider value={value}>
      {!loading && children}
    </AuthContext.Provider>
  );
}
```

### Wrapping the App with the AuthProvider

Modify your **root.jsx** file like given below, by wrapping the **Outlet** component with the **AuthProvider** component.

```js
import {
  Links,
  LiveReload,
  Meta,
  Outlet,
  Scripts,
  ScrollRestoration,
} from "remix";
import styles from "./tailwind.css";
import { AuthProvider } from "./contexts/AuthContext";
import Header from "./components/Header";

export function links() {
  return [{ rel: "stylesheet", href: styles }];
}

export function meta() {
  return { title: "New Remix App" };
}

export default function App() {
  return (
    <html lang="en">
      <head>
        <meta charSet="utf-8" />
        <meta name="viewport" content="width=device-width,initial-scale=1" />
        <Meta />
        <Links />
      </head>
      <body>
        <AuthProvider>
          <Header />
          <hr />
          <Outlet />
        </AuthProvider>
        <ScrollRestoration />
        <Scripts />
        <LiveReload />
      </body>
    </html>
  );
}
```

We have completed the setup, and now we can use firebase authnetication in our project.
In my case I will have the Login Button on my Page Header. You can follow along with the code snippet below.
Note my Header component is present in app/components folder and I am using TailWind for styling.

```js
// Header.js present in app/components folder
import { useAuth } from "~/contexts/AuthContext";

export default function Header() {
  const { signInWithGoogle, currentUser } = useAuth();
  console.log(currentUser);
  return (
    <div className="max-w-3xl mx-auto p-5 flex justify-between items-center">
      {currentUser ? (
        <img
          src={currentUser.photoURL}
          alt="User"
          className="border rounded-full h-10"
        />
      ) : (
        <div onClick={signInWithGoogle}>Login</div>
      )}
    </div>
  );
}
```

Now on clicking the Login button the user will be redirected to the Google sign in pop up page, and after signing in the user will be redirected to the Home page.

You can console.log the **currentUser** object to see the user details.