DEV Community

Lakhan Samani
Lakhan Samani

Posted on

Using authorizer on your Gatsby site

Authorizer is an open source solution for your authentication and authorization needs. It connects with your database and adds a secure auth layer for your users. Aim of authorizer is to have control over your data and not worry about managing authentication and authorization. Consider it as open source version of Auth0 πŸ˜‰

Gatsby is the fast and flexible framework that makes building websites with any CMS, API, or database simpler.

In this post we will see how you can have authentication up and running for free in your Gatsby application with 8 simple steps

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
Enter fullscreen mode Exit fullscreen mode

OR

yarn add @authorizerdev/authorizer-react
Enter fullscreen mode Exit fullscreen mode

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>
    );
}
Enter fullscreen mode Exit fullscreen mode

Step 5: Update browser config

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

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>;
};
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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>
    );
}
Enter fullscreen mode Exit fullscreen mode

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>
    );
}
Enter fullscreen mode Exit fullscreen mode

That's all you need. Secure authentication will be up and running for your application πŸŽ‰.

Here is Github repo that has sample application code: https://github.com/authorizerdev/examples/tree/main/with-gatsbyjs

For more questions please reach out to us on discord channel or pull up an issue on github.
Also don't forget to give us 🌟(star) on github project πŸ₯°

For more information check:

Site: https:://authorizer.dev
Docs: https://docs.authorizer.dev
Youtube: https://youtube.com/playlist?list=PLSQGbUjHc6bpaAgCiQPzNxiUPr7SkDAFR
Github: https://github.com/authorizerdev/authorizer
React-SDK: https://github.com/authorizerdev/authorizer-react
JS-SDK: https://github.com/authorizerdev/authorizer-js
Join Discord: https://discord.gg/Zv2D5h6kkK

Top comments (0)