Gatsby authentication theme with Auth0, Session Context, first-class routing support and full typescript support.
See example site deployed at gatsby-theme-auth0-ts-example.netlify.com.
Jump to comparison with gatsby-theme-auth0
- Easy set up; simply set up your ENV with values from your Auth0 application.
- Full typescript support
- Routing with
<PrivateRoute /> - Access session and auth utilities via the React Context API (
SessionContext)
This setup assumes you are using yarn and dotenv. See the demo app for more details
- Create an auth0 'Single Page Web App' application for your site and configure the auth0 application. An example for development running at
http://localhost:8000:
- Add
http://localhost:8000/auth/callbackto the Allowed Callback URLs field. - Add
http://localhost:8000to Allowed Web Origins and Allowed Logout URLs.
- Add this package to your gatsby site dependencies:
yarn add gatsby-theme-auth0-ts - Add the theme to your
gatsby-config. Environment variables should be filled in from the auth0 app you created.
### .env.development
# ~ Make sure to add me to your .gitignore ~
# Required for Auth0
AUTH0_DOMAIN=<FILL IN FROM YOUR AUTH0 APPLICATION>
AUTH0_CLIENT_ID=<FILL IN FROM YOUR AUTH0 APPLICATION>
AUTH0_CALLBACK_URL=http://localhost:8000/auth/callback
# Optional
AUTH0_AUDIENCE=
AUTH0_RESPONSE_TYPE=
AUTH0_SCOPE=
// gatsby-config.js
require("dotenv").config({
path: `.env.${process.env.NODE_ENV}`,
})
module.exports = {
siteMetadata: {
title: "Gatsby + Auth0 + Ts",
},
plugins: [
{
resolve: "gatsby-theme-auth0-ts",
options: {
/*
Required: for more information on these values
see https://auth0.com/docs/libraries/auth0js/v9#initialization
*/
auth0Domain: process.env.AUTH0_DOMAIN,
auth0ClientID: process.env.AUTH0_CLIENT_ID,
auth0RedirectUri: process.env.AUTH0_CALLBACK_URL,
/* Optional */
// auth0Audience: undefined,
// auth0ResponseType: "token id_token",
// auth0Scope: "openid profile",
},
},
],
}- Begin creating your app. The Example App shows off some of what you can do:
- Programatically create authenticated-only pages: see gatsby-node and the account page.
<PrivateRoute component={MyRoute} />accepts a@reach/routerRouteComponent which will receive and additionaluserprop (or redirect to the authentication flow if the user is not logged in).@reach/routeris used by Gatsby's routing layer so ready to go. - Access the user + session state directly via the React context api: see the Header component.
User (source)
A User object can be either a LoggedInUser or a LoggedOutUser.
<PrivateRoute /> (source)
The PrivateRoute source component is intended to be used within the context of @reach/router. It wraps the internal component prop and passes in a user (LoggedInUser) prop as well. If the user is not logged in PrivateRoute will redirect them to the authentication flow.
import { PrivateRoute, PrivateRouteComponent } from "gatsby-theme-auth0-ts"
const Home: PrivateRouteComponent = ({ user }) => {
return <p>Hi, {user.profile.nickname ? user.profile.nickname : "friend"}!</p>
}
const Account = () => {
return (
<Layout>
<Router>
<PrivateRoute component={Home} path="/account" />
{/* ET CETERA */}
<PrivateRoute component={Settings} path="/account/settings" />
</Router>
</Layout>
)
}SessionContext (source)
The SessionContext is a React Context which provides a Session object containing (in particular) a user and an auth object with helpers for triggering the login and logout flows:
import { SessionContext } from "gatsby-theme-auth0-ts"
const LoginOrOut = () => {
const session = React.useContext(SessionContext)
const { auth } = session
return user.isLoggedIn ? (
<button onClick={() => auth.logout()}>Log Out</button>
) : (
<button onClick={() => auth.authorize()}>Log In</button>
)
}Issues and Pull requests accepted. Contributors must abide by the Contributor Covenant CoC.
@erikdstock
epilande/gatsby-theme-auth0 is another approach to combining gatsby and auth0 developed independently of this package. Both provide typescript support and use a similar auth0 configuration. They differ in that:
- This package uses the
<PrivateRoute />component as the primary method of triggering the authentication flow. - This package exposes session information via the
SessionContext(i.e.React.useContext(SessionContext)) epilande/gatsby-theme-auth0handles authentication primarily via a custom react hook.
- Securing Gatsby with Auth0 and this youtube video featuring @kukicado and @jlengstorf inspired this theme's initial structure.
