SECRET OF CSS

Build a Gatsby Authentication Flow with Firebase | by Marcos Lombog | Jul, 2022


Secure your Gatsby app using Firebase authentication

This guide will walk you through how to set up an authentication flow using Firebase in your Gatsby application, and deploying it to Netlify hosting. After following this guide, you will have a working Gatsby app complete with:

  • Fully fledged sign-in and sign-up flows.
  • Secure email/password authentication.
  • Reset password
  • A secure user profile page.
  • Deployment to Netlify

A working demo app is available here. Full source code provided.

Created in 2015, Gatsby is an open-source static site generator built on top of Node.js using React and GraphQL. It provides over 2500 plugins to create static sites based on sources as Markdown documents, MDX, images, and numerous Content Management Systems such as WordPress, Drupal and more. It’s lightning fast because of the server side renders of JavaScript into static site files that are minified and can be served through a content delivery network.

Since all the pages in Gatsby are rendered as static content, user authentication to your Gatsby site can’t be performed on the server, but must be protected through client-side routing.

This tutorial will walk you through setting up client-side Authentication in Gatsby using a robust solution to handle the authentication such as Firebase, and how to manage logged-in users in your Gatsby app.

Our starting point is the simple authentication flow available in the Gatsby examples folder. I’ve forked the Gatsby project and created a starting point here with the simple-auth: https://github.com/mlomboglia/simple-auth

Just clone the project:

$ git clone https://github.com/mlomboglia/simple-auth$ cd simple-auth

I’m assuming you already have NodeJS installed. If not, you can install it here:

Upgrade to the latest Gatsby version

On your project root folder

$ npm install gatsby@latest --legacy-peer-deps

Firebase Authentication provides backend services, easy-to-use SDKs, and ready-made UI libraries to authenticate users to your app. It supports authentication using passwords, phone numbers, popular federated identity providers like Google, Facebook and Twitter, and more.

Firebase Authentication integrates tightly with other Firebase services, and it leverages industry standards like OAuth 2.0 and OpenID Connect, so it can be easily integrated with your custom backend.

For this demo, I will set up an email/password authentication provider. Many other options are available.

Open Firebase console.

Add a new project, select a name, and create project:

1*82fNhV4fRz5sGvobbZNySQ

Click on Web Icon, to add a new Web App:

1*bD L3UofzbvsNzRgBmGqww

Copy the Firebase config items, and save them for later.

I will add them as environment variables.

Click on Authentication.

1*GIbKy9oIeeWNDKTztvIMcQ

Enable the Email / Password option.

1*56EP7tGnNTUrdovDhMYiug

On your project root folder, install Firebase SDK

$ npm i firebase

Firebase component

Now, let’s create the Firebase component.

Open your favourite IDE. I’m using Visual Studio Code.

Create a folder Firebase on your src/components.

Create Firebase.js file:

Environment variables

Gatsby has built-in support for loading environment variables into the browser and Functions.

To load these into Node.js, add the following code snippet to the top of your gatsby-config.js file:

require("dotenv").config({
path: `.env.${process.env.NODE_ENV}`,
})

In development, Gatsby will load environment variables from a file named .env.development. For builds, it will load from .env.production.

Create a file env.development in the root folder of the project.

Add the following variables:

GATSBY_FIREBASE_API_KEY=<from firebase console config>
GATSBY_FIREBASE_AUTH_DOMAIN=<from firebase console config>
GATSBY_FIREBASE_DATABASE_URL=<from firebase console config>
GATSBY_FIREBASE_PROJECT_ID=<from firebase console config>
GATSBY_FIREBASE_STORAGE_BUCKET=<from firebase console config>
GATSBY_FIREBASE_MESSAGING_SENDER_ID=<from firebase console config>
GATSBY_FIREBASE_APP_ID=<from firebase console config>
GATSBY_FIREBASE_MEASUREMENT_ID=<from firebase console config>

Add .env* files to .gitignore

Environment variable files should not be committed to Git as they often contain secrets that are not safe to add to Git. Instead, add .env.* to your .gitignore file and set up the environment variables manually on Gatsby Cloud and locally.

To manage the state of our user at a global level throughout our Gatsby site, we will implement the React Context API. Let’s wrap the Gatsby root element in our Context provider to ensure that our Context value will be available to all of our consuming components in our app.

More on Context is available in the React documentation.

Context

Create an Auth folder inside the components folder.

Create the AuthContext.js file.

In order for all of our components in our app to become a context consumer we need to wrap our custom <AuthProvider> component around the Gatsby root element.

Let’s use a helper functional wrapRootElement component in our AuthContext.js file that exported our <AuthProvider> component wrapped around the { element } prop that will be passed in to our wrapRootElement function. All we need to do now is use gatsby-browser.js to import (and immediately export) our wrapRootElement function.

Open gatsby-browser.js in the project directory and add:

Status

The Status component will show the authenticated user or not.

Edit the index.js inside the Status folder:

To create a site with gated content, restricted to only authenticated users, we can achieve this using the concept of client-only routes, to define which pages a user can view only after logging in.

Using the @reach/router library, you can create routes available only to logged-in users. This library is used by Gatsby under the hood, so you don’t even have to install it.

First, create gatsby-node.js in root directory of your project. You will define that any route that starts with /app/ is part of your restricted content and the page will be created on demand:

Now we’re going to create a page in our ./src/pages/ folder called app.js which will import our components and use a helper from the @reach/router library to handle client only dynamic routing. Create the file in ./src/pages/app.js which will look like this:

Login Route

For the Login component, I will use signInWithEmailAndPassword method available in firebase/auth library:

Create Login.js in the components folder

Register Route

To register a user, we can use the createUserWithEmailAndPassword method available in firebase/auth component:

Create Register.js in the components folder

Reset Password Route

Similar for password reset, I will use the sendPasswordResetEmail

Create Reset.js:

Firebase allows you to customize your email domain, and email template message for password reset.

Private Route Component

The <PrivateRoute /> component will verify is the user is authenticated or not. If the current user exists, it will load the gated component.

Create PrivateRoute.js in the components folder.

Secure Profile Route

The Profile Route will be loaded if the user is authenticated.

Create Profile.js in components folder.

Header

On your Header/index.js adjust the link to <Link to=”/app/profile” className={header__link}>

Now we are ready to test the app

Run your app using $ gatsby develop

Open http://localhost:8000/

1*H5WQJ Y3KZ4y5dzvbme tQ

Register a new user, log in to navigate to the Profile screen.

A working demo app is available here

The complete source code is available here:

Let’s deploy our app to Netlify.

Commit all your code in your favourite Git provider, such as Github.

Create a Netlify account (it’s free to signup), if you don’t have one.

Step 1: Add Your New Site

Click the Add A New Site → Import from template option

Step 2: Link to Your Git Provider (or supported version-control tool of choice)

I’m using GitHub. Push your repo to GitHub, so that all we’ll need to do is link Netlify to GitHub. Click the GitHub button as illustrated in the screenshot above.

Step 3: Authorize Netlify

If it’s not authorized, allow Netlify and GitHub to talk to each other by clicking the Authorize option.

Step 4: Select Your Repo

Now that you’ve connected Netlify and GitHub, you can see a list of your Git repos. Choose the repo you’d like to deploy from the list. Click Deploy site

After a few minutes, you should your new site listed.

Step 5: Configure Your Settings

1*qzVJMmjvd2q07 NdyB zWQ

Click on Site settings → Build & Deploy → Environment

Add your environment variables, as you have them in the env.development file.

Step 6: Build Your Site

Rebuild your site!

Step 7: Authorize your domain in Firebase

Now, we need to authorize the new domain in Firebase

Go to your Firebase console → Authentication → Settings

Click on Add Domain, and add your Netlify deployed app domain to the authorized list

Step 8: Test Your App in Netlify

Click on your app URL in Netlify, and you should have a complete working version of the Gatsby Authentication Flow with Firebase deployed

Done!



News Credit

%d bloggers like this: