Skip to content

Latest commit

 

History

History

with-gatsbyjs

Folders and files

README.md

Gatsby

With Gatsby

Quick start

  • Get with-gatsby example
  • Change directory cd with-gatsby
  • Install dependencies npm i
  • Start locally npm start

Note: This example uses Gatsby 4, whose native dependencies (lmdb-store) do not compile on Node.js 20+. Use Node.js 16–18 to run it.

Authorizer v2 server is configured entirely via CLI flags (no .env / OS env vars), e.g.

./authorizer \
  --database-type sqlite --database-url authorizer.db \
  --url http://localhost:8080 \
  --jwt-type HS256 --jwt-secret <jwt-secret> \
  --encryption-key "$(openssl rand -hex 32)" \
  --client-id <client-id> --client-secret <client-secret> \
  --admin-secret <admin-secret>

All of the above are required as of 2.4.0 — the server exits at boot if any is missing. --url is this server's own address (not the apps allowed to call it, which is --allowed-origins).

Using Authorizer with Gatsby

Step 1: Get Authorizer Instance

Deploy production ready Authorizer instance using one click deployment options available below

Infra provider One-click link Additional information
Railway.app Deploy on Railway docs
Heroku Deploy to Heroku docs
Render render button docs

For more information check docs

Step 2: Setup Instance

  • Open authorizer instance endpoint in browser
  • Signup with a secure password
  • Configure social logins / smtp server and other environment variables based on your needs

For more information please check docs

Step 3: Bootstrap Gatsby Site

Run npm init gatsby this will call create-gatsby and help you bootstrap gatsby site

Answer the few bootstrapping questions,

  • Give your site a name
  • Select the repo name
  • Select CMS (For demo purpose I did not select any cms)
  • Selected styled-components for styling system
  • Select the additional features you want

Step 3: Install @authorizerdev/authorizer-react

npm install @authorizerdev/authorizer-react

OR

yarn add @authorizerdev/authorizer-react

Then import the SDK stylesheet once, e.g. in gatsby-browser.js:

require('@authorizerdev/authorizer-react/styles.css');

Step 4: Create Root Layout

Create src/components/layout.js as the root layout for app with AuthorizerProvider

Note: Replace YOUR_AUTHORIZER_URL with your authorizer instance URL obtained on step 2. Also replace YOUR_CLIENT_ID with your client ID obtained from dashboard in step 2.

import React from 'react';
import { AuthorizerProvider } from '@authorizerdev/authorizer-react';

// styles
const pageStyles = {
	color: '#232129',
	padding: 96,
	fontFamily: '-apple-system, Roboto, sans-serif, serif',
};

export default function Layout({ children }) {
	return (
		<AuthorizerProvider
			config={{
				authorizerURL: 'YOUR_AUTHORIZER_URL',
				redirectURL:
					typeof window !== 'undefined' ? window.location.origin : '/',
				clientID: 'YOUR_CLIENT_ID',
			}}
		>
			<div
				style={{
					margin: `0 auto`,
					maxWidth: 650,
					padding: `0 1rem`,
					...pageStyles,
				}}
			>
				{children}
			</div>
		</AuthorizerProvider>
	);
}

Step 5: Update browser config

Add root layout in gatsby browser config. Create gatsby-browser.js in the root of project with following content

require('@authorizerdev/authorizer-react/styles.css');

const React = require('react');
const Layout = require('./src/components/layout').default;

// Wraps every page in a component
exports.wrapPageElement = ({ element, props }) => {
	return <Layout {...props}>{element}</Layout>;
};

This will prevent re-rendering of layout every time the page changes.

Step 6: Add Authorizer component

Add Authorizer component in src/pages/index.js page with redirects.

Here in case if user is logged in we would like to redirect them to private route using useEffect

Replace content of Index page with following

import { Authorizer, useAuthorizer } from '@authorizerdev/authorizer-react';
import * as React from 'react';
import { navigate } from 'gatsby';

const IndexPage = () => {
	const { loading, user } = useAuthorizer();
	React.useEffect(() => {
		if (!loading && user) {
			navigate('/private/dashboard');
		}
	}, [loading, user]);

	if (loading) {
		return <h3>loading...</h3>;
	}

	return (
		<main>
			<Authorizer
				onSignup={() => {
					navigate('/private/dashboard');
				}}
				onLogin={() => {
					navigate('/private/dashboard');
				}}
			/>
		</main>
	);
};

export default IndexPage;

Step 7: Add private route layout

Add src/components/private.js with following content

Here if user is not logged in we would redirect them to home page where we have our Authorizer login component. This also adds logout button which will be common for all private routes

import * as React from 'react';
import { useAuthorizer } from '@authorizerdev/authorizer-react';
import { navigate } from 'gatsby';

export default function PrivateLayout({ children }) {
	const { user, loading, authorizerRef, setUser } = useAuthorizer();
	React.useEffect(() => {
		if (!loading && !user) {
			navigate('/');
		}
	}, [loading, user]);

	const handleLogout = async () => {
		await authorizerRef.logout();
		setUser(null);
		navigate('/');
	};

	if (loading) {
		return <h3>loading...</h3>;
	}

	return (
		<div
			style={{
				margin: `0 auto`,
				maxWidth: 650,
				padding: `0 1rem`,
			}}
		>
			<button onClick={handleLogout}>Logout</button>
			{children}
		</div>
	);
}

Step 7: Add private route

Add src/pages/private/dashboard.js with following content

import * as React from 'react';
import { useAuthorizer } from '@authorizerdev/authorizer-react';
import PrivateLayout from '../../components/private';

export default function Dashboard() {
	const { user } = useAuthorizer();
	return (
		<PrivateLayout>
			<code>{JSON.stringify(user, null, 2)}</code>
		</PrivateLayout>
	);
}