A simple starter to get up and developing quickly with Gatsby and Firebase (reactfire).
-
Create a Gatsby site.
Use the Gatsby CLI to create a new site, specifying the hello-world starter.
# create a new Gatsby site using the reactfire-authentication starter gatsby new reactfire-auth-starter https://github.com/cour64/gatsby-reactfire-authentication-starter
-
Start developing.
Navigate into your new site’s directory and start it up.
cd reactfire-auth-starter/ gatsby develop
-
Test the login.
Go to localhost:8000 and test the default login using the credentials: email: [email protected] password: 123456
-
Create a firebase account.
Create a firebase account, sign in and get your config object. A simple guide on how to get started with firebase is available here.
-
Copy you firebase config object.
Once you have your own config object copy it into the
gatsby-browser.js
file.
This starter builds on top of the official Gatsby default starter. It adds authentication using the firebase service. Firebase is managed using the latest version of the community developed Reactfire library.
firebase
: The firebase JS SDKreactfire
: Used to manage auth state and provide utility hooks for accessing the firebase SDK@reach/router
: Used to handle client-side routing
Apart from the files found inside the default gatsby starter here are a few additions:
-
login.js
: This is a simple form that uses theuseFirebaseApp()
hook to get access to the firebase signIn method within the firebase JS SDK. -
user-hub.js
: This is a simple page which takes over the routing on the client-side. It ensures the user is authenticated and has permissions to access all it's routes that are defined using theAuthCheck
component.
This starter uses the Reactfire library to give you access to firebase using the hooks it provides. The Reactfire library needs a context provider to use the hooks, we setup the context provider by wrapping the root element like so:
// gatsby-browser.js
const wrapRootElement = ({ element }) => (
<FirebaseAppProvider firebaseConfig={firebaseConfig}>
{element}
</FirebaseAppProvider>
)
Once the context provider is setup the firebase JS SDK can be retrieved via hooks. Authentication is handled using client-only routing. The nifty AuthCheck
component, provided by Reactfire, can be used to listen to the sign in state and redirect if the user tries to access a protected page or signs out. The AuthCheck
component works with custom claims too giving you fine grained control over user roles and permissions.