Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Gatsby hide API-keys on the frontend

Tags:

shopify

gatsby

So, I'm struggling to understand how Gatsby works. I'm using the https://www.gatsbyjs.org/starters/AlexanderProd/gatsby-shopify-starter/ which uses a Gatsby plugin called gatsby-source-shopify. The plugin takes two params: shopName and accessToken. It looks like this in gatsby-config.js:

{
  resolve: `gatsby-source-shopify`,
  options: {
    // The domain name of your Shopify shop. This is required.
    shopName: process.env.SHOP_NAME,

    // An API access token to your Shopify shop. This is required.
    accessToken: process.env.SHOPIFY_ACCESS_TOKEN,
  },
},

Will the access token be available for people to look at when I deploy the app? Do I need to use something like Serverless functions to hide my API keys, or is this fine. Any general explanation of how this works in Gatsby would be awesome.

Thanks Gatsby fam!

like image 497
Hans Martin Hanken Avatar asked Nov 26 '25 23:11

Hans Martin Hanken


1 Answers

As the code shows, it uses process.env.SHOP_NAME where SHOP_NAMEis the name of the environment variable. Those files are declared at the root of the project using some naming such as .env.domain1.com. In this file, you can store any desired variable to use it in your Gatsby configurations. When dealing with delicate variables (API keys, tokens, passwords, etc) it's recommended to use that way and ignore all .env files in your .gitignore.

When you trigger a command in Gatsby, you can pass it some variables, for example:

"develop": "GATSBY_ACTIVE_ENV=domain1.com gatsby develop"

In this case, GATSBY_ACTIVE_ENV var will have domain1.com as a value. Then, in you gataby-config.js, when you can use environment variables (above module.exports):

require("dotenv").config({
  path: `.env.${process.env.NODE_ENV}`,
})

Then, you can create an environment file such as .env.domain1.com in your root project and store any desired variable:

SHOP_NAME: 12345

Taking into account the code you've provided if you run develop (with all I've explained) command it will take SHOP_NAME as 12345.

So, answering your question, you won't have access to that tokens. You need to store them in your local machine and in your deploy server, not in your repository. From Gatsby docs:

Please note that you shouldn’t commit .env.* files to your source control and rather use options given by your Continuous Deployment (CD) provider...

Edit: Thanks to @Hans Martin Henken for providing the following article about Gatsby security

like image 98
Ferran Buireu Avatar answered Dec 02 '25 04:12

Ferran Buireu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!