May 10, 2020 by Kostas Vrouvas

How to setup Gatsby ENV variables for Auth0 on Netlify or Vercel

Hey folks,

so I recently wanted to integrate Auth0 on a new web app we are working on and followed this awesome tutorial by Sam Julien.

On development everything works as expected but when deploying on Vercel or Netlify, you are greeted by a Domain Option is Required Error.

There is not much Google results on this, so after a few hours of wondering about my existence I found the solution.

Now, as mentioned in the Gatsby documentation:

For Project Env Vars that you want to access in client-side browser JavaScript, you can define an environment config file, .env.development and/or .env.production, in your root folder. Depending on your active environment, the correct one will be found and its values embedded as environment variables in the browser JavaScript.

In addition to these Project Environment Variables defined in .env.* files, you could also define OS Env Vars. OS Env Vars which are prefixed with GATSBY_ will become available in browser JavaScript.

The Gatsby Docs, probably

So taking this in mind, on every variable you will need to add the GATSBY_ prefix. Like so:

# Get these values at https://manage.auth0.com
GATSBY_AUTH0_DOMAIN=<value>
GATSBY_AUTH0_CLIENTID=<value>
GATSBY_AUTH0_CALLBACK=<value>

And also change these at the auth.js file:

// src/utils/auth.js
import auth0 from "auth0-js"

const isBrowser = typeof window !== "undefined"

const auth = isBrowser
  ? new auth0.WebAuth({
      domain: process.env.GATSBY_AUTH0_DOMAIN,
      clientID: process.env.GATSBY_AUTH0_CLIENTID,
      redirectUri: process.env.GATSBY_AUTH0_CALLBACK,
      responseType: "token id_token",
      scope: "openid profile email",
    })
  : {}

Now this will work just fine on production but will probably break your local development. You will need to change these variables on your .env.development file, too:

# ./.env.development
# Get these values at https://manage.auth0.com
GATSBY_AUTH0_DOMAIN=<value>
GATSBY_AUTH0_CLIENTID=<value>
GATSBY_AUTH0_CALLBACK=http://localhost:8000/callback

And that’s all!

© 2020 Kostas Vrouvas, Built with Gatsby