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

Safe your Gatsby app utilizing Firebase authentication

This information will stroll you thru arrange an authentication stream utilizing Firebase in your Gatsby software, and deploying it to Netlify internet hosting. After following this information, you’ll have a working Gatsby app full with:

  • Absolutely fledged sign-in and sign-up flows.
  • Safe e mail/password authentication.
  • Reset password
  • A safe consumer profile web page.
  • Deployment to Netlify

A working demo app is on the market here. Full supply code supplied.

Created in 2015, Gatsby is an open-source static web site generator constructed on prime of Node.js utilizing React and GraphQL. It gives over 2500 plugins to create static websites based mostly on sources as Markdown paperwork, MDX, photographs, and quite a few Content material Administration Techniques corresponding to WordPress, Drupal and extra. It’s lightning quick due to the server aspect renders of JavaScript into static web site recordsdata which are minified and could be served by means of a content material supply community.

Since all of the pages in Gatsby are rendered as static content material, consumer authentication to your Gatsby web site can’t be carried out on the server, however have to be protected by means of client-side routing.

This tutorial will stroll you thru establishing client-side Authentication in Gatsby utilizing a sturdy answer to deal with the authentication corresponding to Firebase, and handle logged-in customers in your Gatsby app.

Our start line is the easy authentication stream out there within the Gatsby examples folder. I’ve forked the Gatsby undertaking and created a place to begin right here with the simple-auth: https://github.com/mlomboglia/simple-auth

Simply clone the undertaking:

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

I’m assuming you have already got NodeJS put in. If not, you may set up it right here:

Improve to the most recent Gatsby model

In your undertaking root folder

$ npm set up gatsby@newest --legacy-peer-deps

Firebase Authentication gives backend companies, easy-to-use SDKs, and ready-made UI libraries to authenticate customers to your app. It helps authentication utilizing passwords, cellphone numbers, standard federated id suppliers like Google, Fb and Twitter, and extra.

Firebase Authentication integrates tightly with different Firebase companies, and it leverages trade requirements like OAuth 2.0 and OpenID Join, so it may be simply built-in together with your customized backend.

For this demo, I’ll arrange an e mail/password authentication supplier. Many different choices can be found.

Open Firebase console.

Add a brand new undertaking, choose a reputation, and create undertaking:

Click on on Internet Icon, so as to add a brand new Internet App:

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

I’ll add them as atmosphere variables.

Click on on Authentication.

Allow the E-mail / Password possibility.

In your undertaking root folder, set up Firebase SDK

$ npm i firebase

Firebase element

Now, let’s create the Firebase element.

Open your favorite IDE. I’m utilizing Visible Studio Code.

Create a folder Firebase in your src/parts.

Create Firebase.js file:

Setting variables

Gatsby has built-in assist for loading atmosphere variables into the browser and Features.

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

require("dotenv").config(
path: `.env.$course of.env.NODE_ENV`,
)

In growth, Gatsby will load atmosphere variables from a file named .env.growth. For builds, it’s going to load from .env.manufacturing.

Create a file env.growth within the root folder of the undertaking.

Add the next 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* recordsdata to .gitignore

Setting variable recordsdata shouldn’t be dedicated to Git as they usually comprise secrets and techniques that aren’t secure so as to add to Git. As a substitute, add .env.* to your .gitignore file and arrange the atmosphere variables manually on Gatsby Cloud and regionally.

To handle the state of our consumer at a worldwide degree all through our Gatsby web site, we are going to implement the React Context API. Let’s wrap the Gatsby root component in our Context supplier to make sure that our Context worth might be out there to all of our consuming parts in our app.

Extra on Context is on the market within the React documentation.

Context

Create an Auth folder contained in the parts folder.

Create the AuthContext.js file.

To ensure that all of our parts in our app to grow to be a context client we have to wrap our customized <AuthProvider> element across the Gatsby root component.

Let’s use a helper purposeful wrapRootElement element in our AuthContext.js file that exported our <AuthProvider> element wrapped across the component prop that might be handed in to our wrapRootElement operate. All we have to do now could be use gatsby-browser.js to import (and instantly export) our wrapRootElement operate.

Open gatsby-browser.js within the undertaking listing and add:

Standing

The Standing element will present the authenticated consumer or not.

Edit the index.js contained in the Standing folder:

To create a web site with gated content material, restricted to solely authenticated customers, we are able to obtain this utilizing the idea of client-only routes, to outline which pages a consumer can view solely after logging in.

Utilizing the @reach/router library, you may create routes out there solely to logged-in customers. This library is utilized by Gatsby beneath the hood, so that you don’t even have to put in it.

First, create gatsby-node.js in root listing of your undertaking. You’ll outline that any route that begins with /app/ is a part of your restricted content material and the web page might be created on demand:

Now we’re going to create a web page in our ./src/pages/ folder referred to as app.js which can import our parts and use a helper from the @attain/router library to deal with consumer solely dynamic routing. Create the file in ./src/pages/app.js which can appear to be this:

Login Route

For the Login element, I’ll use signInWithEmailAndPassword technique out there in firebase/auth library:

Create Login.js within the parts folder

Register Route

To register a consumer, we are able to use the createUserWithEmailAndPassword technique out there in firebase/auth element:

Create Register.js within the parts folder

Reset Password Route

Related for password reset, I’ll use the sendPasswordResetEmail

Create Reset.js:

Firebase means that you can customise your e mail area, and e mail template message for password reset.

Personal Route Part

The <PrivateRoute /> element will confirm is the consumer is authenticated or not. If the present consumer exists, it’s going to load the gated element.

Create PrivateRoute.js within the parts folder.

Safe Profile Route

The Profile Route might be loaded if the consumer is authenticated.

Create Profile.js in parts folder.

Header

In your Header/index.js regulate the hyperlink to <Hyperlink to=”/app/profile” className=header__link>

Now we’re prepared to check the app

Run your app utilizing $ gatsby develop

Open http://localhost:8000/

Register a brand new consumer, log in to navigate to the Profile display.

A working demo app is on the market here

The entire supply code is on the market right here:

Let’s deploy our app to Netlify.

Commit all of your code in your favorite Git supplier, corresponding to Github.

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

Step 1: Add Your New Website

Click on the Add A New Website → Import from template possibility

Step 2: Hyperlink to Your Git Supplier (or supported version-control device of alternative)

I’m utilizing GitHub. Push your repo to GitHub, so that each one we’ll have to do is hyperlink Netlify to GitHub. Click on the GitHub button as illustrated within the screenshot above.

Step 3: Authorize Netlify

If it’s not approved, permit Netlify and GitHub to speak to one another by clicking the Authorize possibility.

Step 4: Choose Your Repo

Now that you just’ve linked Netlify and GitHub, you may see an inventory of your Git repos. Select the repo you’d wish to deploy from the record. Click on Deploy web site

After a couple of minutes, it is best to your new web site listed.

Step 5: Configure Your Settings

Click on on Website settings → Construct & Deploy → Setting

Add your atmosphere variables, as you’ve them within the env.growth file.

Step 6: Construct Your Website

Rebuild your web site!

Step 7: Authorize your area in Firebase

Now, we have to authorize the brand new area in Firebase

Go to your Firebase console → Authentication → Settings

Click on on Add Area, and add your Netlify deployed app area to the approved record

Step 8: Check Your App in Netlify

Click on in your app URL in Netlify, and it is best to have an entire working model of the Gatsby Authentication Movement with Firebase deployed

Completed!

More Posts