Docs

You are viewing an archived version of the docs.Go to latest version

Use Clerk with Gatsby

Learn how to use Clerk to quickly and easily add secure authentication and user management to your Gatsby application.

Install gatsby-plugin-clerk

Clerk's Gatsby SDK has prebuilt components, React hooks, and helpers to make user authentication easier.

To get started using Clerk with Gatsby, add the SDK to your project:

terminal
npm install gatsby-plugin-clerk
terminal
yarn add gatsby-plugin-clerk
terminal
pnpm add gatsby-plugin-clerk

Set environment variables

Below is an example of your .env.development file.

Pro tip! If you are signed into your Clerk Dashboard, your secret key should become visible by clicking on the eye icon. Otherwise, you can find your keys in the Clerk Dashboard on the API Keys page.

.env.development
GATSBY_CLERK_PUBLISHABLE_KEY=YOUR_PUBLISHABLE_KEY
CLERK_SECRET_KEY=YOUR_SECRET_KEY

Update gatsby-config.ts

To use Clerk, you will need to update your gatsby-config.ts in order to resolve gatsby-plugin-clerk and load from .env files.

gatsby-config.ts
import type { GatsbyConfig } from "gatsby"

require("dotenv").config({
  path: `.env.${process.env.NODE_ENV}`,
})
const config: GatsbyConfig = {
  siteMetadata: {
    title: `clerk-test`,
    siteUrl: `https://www.yourdomain.tld`,
  },
  // Add Gatsby plugin
  plugins: [
    {
      resolve: `gatsby-plugin-clerk`
    },
  ],
}

export default config

Protecting your pages

Clerk offers Control Components that allow you to protect your pages. These components are used to control the visibility of your pages based on the user's authentication state.

src/pages/index.tsx
import React from 'react'
import {
  SignIn,
  SignedIn,
  RedirectToSignIn,
  SignedOut,
  UserButton
  } from 'gatsby-plugin-clerk'

export default function IndexPage() {
  return (
    <>
      <SignedIn>
        <UserButton />
      </SignedIn>
      <SignedOut>
        <RedirectToSignIn />
      </SignedOut>
    </>
  )
}

Read sesssion and user data

Clerk provides a set of hooks and helpers that you can use to access the active session and user data in your React application. Here are examples of how to use these helpers.

useAuth

The useAuth hook is a convenient way to access the current auth state. This hook provides the minimal information needed for data-loading and helper methods to manage the current active session.

src/pages/example.tsx
import { useAuth } from "gatsby-plugin-clerk";

export default function Example() {
  const { isLoaded, userId, sessionId, getToken } = useAuth();

  // In case the user signs out while on the page.
  if (!isLoaded || !userId) {
    return null;
  }

  return (
    <div>
      Hello, {userId} your current active session is {sessionId}
    </div>
  );
}

useUser

The useUser hook is a convenient way to access the current user data where you need it. This hook provides the user data and helper methods to manage the current active session.

src/pages/example.tsx
import { useUser } from "gatsby-plugin-clerk";

export default function Example() {
  const { isLoaded, isSignedIn, user } = useUser();

  if (!isLoaded || !isSignedIn) {
    return null;
  }

  return <div>Hello, {user.firstName} welcome to Clerk</div>;
}
src/pages/SSRPage.tsx
import * as React from 'react';
import { GetServerData } from 'gatsby';
import { withServerAuth } from 'gatsby-plugin-clerk/ssr';

export const getServerData: GetServerData<any> = withServerAuth(
  async props => {
    return { props: { data: '1', auth: props.auth } };
  },
  { loadUser: true },
);

function SSRPage({ serverData }: any) {
  return (
    <main>
      <h1>SSR Page with Dogs</h1>
      <pre>{JSON.stringify(serverData, null, 2)}</pre>
    </main>
  );
}

export default SSRPage;

Next steps

Now that you have an application integrated with Clerk, you will want to read the following documentation:

Customization & Localization

Learn how to customize and localize the Clerk components.

Authentication Components

Learn more about all our authentication components.

Client Side Helpers

Learn more about our client side helpers and how to use them.

Feedback

What did you think of this content?

Last updated on