> For the complete documentation index, see [llms.txt](https://docs.chord.co/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.chord.co/chord-oms/developer-tools/authentication/stytch/stytch-migration-guides/gatsby-stytch-migration-guide.md).

# Gatsby ↔️ Stytch Migration Guide

## Stytch Account Setup

Create your Stytch account following our [Stytch Account Setup](/chord-oms/developer-tools/authentication/stytch/stytch-account-setup.md) guide.

## Add your public key to the .env

You can find your [public token](https://stytch.com/dashboard/api-keys) in the Stytch dashboard.

```shell
GATSBY_PUBLIC_STYTCH_API_KEY={your_token}
```

Also remove the magic key from your .env if you have one.

## Install Stytch and gatsby-theme-autonomy

```shell
npm install @stytch/nextjs @stytch/vanilla-js @chordcommerce/gatsby-theme-autonomy@^5.0.0
```

## Add a StytchProvider

Create a new file called "AuthProvider" and paste the following code:

{% code title="StytchProvider" %}

```javascript
import React from 'react'
import { StytchProvider } from '@stytch/nextjs'
import { useAuth } from '@chordcommerce/react-autonomy'

const AuthProvider = ({ children }) => {
  const { serviceClient } = useAuth()
  return <StytchProvider stytch={serviceClient}>{children}</StytchProvider>
}

export default AuthProvider
```

{% endcode %}

Then wrap `element` in your `gatsby-browser.js` file with the `AuthProvider`:

```javascript
<AuthProvider>{element}</AuthProvider>
```

## Add a LoginForm component that uses StytchLogin

Go to the [config docs](https://stytch.com/docs/sdks/javascript-sdk#ui-config) to see what options are available.

{% code title="AuthLoginForm" %}

```javascript
import React from 'react'
import { StytchLogin, StytchProvider } from '@stytch/nextjs'
import { createStytchUIClient } from '@stytch/nextjs/ui'
import { useMemo } from 'react'
import { useAuth } from '@chordcommerce/react-autonomy'
import { navigate } from 'gatsby'

const AuthLoginForm = () => {
  let baseUrl
  if (typeof window !== 'undefined') baseUrl = window.location.origin

  const { getToken, serviceClient } = useAuth()

  const stytchProps = useMemo(
    () => ({
      config: {
        products: ['emailMagicLinks', 'oauth'],
        emailMagicLinksOptions: {
          loginRedirectURL: `${baseUrl}/authenticate`,
          loginExpirationMinutes: 30,
          signupRedirectURL: `${baseUrl}/authenticate`,
          signupExpirationMinutes: 30,
        },
        // these won't work until you have set them up in Stytch
        oauthOptions: {
          loginRedirectURL: `${baseUrl}/authenticate`,
          signupRedirectURL: `${baseUrl}/authenticate`,
          providers: [{ type: 'google' }],
        },
      },
      styles: {
        hideHeaderText: true,
        width: '100%',
        primaryColor: '#215732',
      },
      callbacks: {
        // this function will automatically navigate to the /account page when a user clicks
        // the magic link in their email and is authenticated on another tab
        onEvent: async () => {
          const intervalID = setInterval(async () => {
            if (serviceClient?.session.getSync()) {
              await getToken()
              clearInterval(intervalID)
              navigate('/account')
            }
          }, 1000)
        },
        // this function logs the error message in segment
        onError: (message) => {
          window.analytics.track({
            message,
            meta: {
              storeId: process.env.GATSBY_CHORD_OMS_STORE_ID,
              omsId: process.env.GATSBY_CHORD_OMS_ID,
              tenantId: process.env.GATSBY_CHORD_OMS_TENANT_ID,
              currency: 'USD',
              locale: 'en-US',
            },
          })
        },
      },
    }),
    [baseUrl, getToken, serviceClient]
  )

  return (
    <StytchProvider
      stytch={createStytchUIClient(
        process.env.GATSBY_PUBLIC_STYTCH_API_KEY
      )}
    >
      <StytchLogin
        config={stytchProps.config}
        styles={stytchProps.styles}
        callbacks={stytchProps.callbacks}
      />
    </StytchProvider>
  )
}

export default AuthLoginForm
```

{% endcode %}

## Create an Authenticate component

This component will authenticate the user by calling `handleCallback()` from useAuth, then it will navigate to the /account page.

Add this component to the pages directory:

{% code title="Authenticate" %}

```javascript
import React, { useEffect } from 'react'
import { useAuth } from '@chordcommerce/react-autonomy'
import { navigate } from 'gatsby'

const Authenticate = () => {
  const { handleCallback } = useAuth()

  useEffect(() => {
    handleCallback().then(() => navigate('/account'))
  }, [])

  return <>Loading...</>
}

export default Authenticate
```

{% endcode %}

## Try it out

Visit your login page and try logging in using a magic link!

Once you've clicked the link in the email from Stytch to sign-up/login, you can visit the [user management](https://stytch.com/dashboard/user-management) page to see your user.

## Enabling OAuth

If your would like to enable OAuth, visit the [SDK Configuration](https://stytch.com/dashboard/sdk-configuration) page, and click the OAuth toggle. Then, expand the OAuth section and toggle Enable PKCE.

Once OAuth is enabled, visit the [OAuth page](https://stytch.com/dashboard/oauth), then select the provider you would like to use and follow the directions.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.chord.co/chord-oms/developer-tools/authentication/stytch/stytch-migration-guides/gatsby-stytch-migration-guide.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
