Site-wide authentication using context within Gatsby
There may be situations where you want the entirety of your Gatsby site to be behind authentication. For example, you may have made a documentation site only meant for employees of your company. Let's look at how we can use context to turn every page into a private route:
- First, let's create a login component in the
components
folder. Call this fileLogin.js
and add the following code to it:import React from "react"; const Login = ({login}) => { return <button onClick={login}>Login</button>; }; export default Login;
You'll notice that, unlike the last
Login
component we created, we are not retrieving thelogin
function from the context. The reason for this will become clear when we create the context. - Create a folder called
context
insrc
. - Create a file in
context
calledauth-context.js
and add the following code:import React, { useState, useContext } from "react"...