---
title: Gatsby ↔️ Stytch Migration Guide
slug: oms/gatsby-stytch-migration-guide
docTags: 
createdAt: 2022-11-03T18:36:58.000Z
---

## Stytch Account Setup

Create your Stytch account following our [Stytch Account Setup](docId\:ssTgzaJO30Gx2Bs9QdOlS) 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:

::::CodeDrawer{title="StytchProvider" isResponseExpanded="false" autoGeneratedAnchorSlug="stytchprovider" legacyHash="BSK0Xgx2pcNMfpNVYAPFp"}
:::CodeblockTabsExamples
```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
```
:::

:::CodeblockTabsResponses
```javascript
```
:::
::::

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.

::::CodeDrawer{title="AuthLoginForm" isResponseExpanded="false" autoGeneratedAnchorSlug="authloginform" legacyHash="6uHtqyjv-g5Ollcu82wBO"}
:::CodeblockTabsExamples
```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
```
:::

:::CodeblockTabsResponses
```javascript
```
:::
::::

## 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:

::::CodeDrawer{title="Authenticate" isResponseExpanded="false" autoGeneratedAnchorSlug="authenticate" legacyHash="0vPjD1yLSoALv5zru5EPO"}
:::CodeblockTabsExamples
```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
```
:::

:::CodeblockTabsResponses
```javascript
```
:::
::::

## 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.

