Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Gatsby env variables in a mdx file?

Tags:

gatsby

I am trying to display Gatsby env variables in md file. I checked online what was the best way to do it, and using JSX in a md file (with the help of mdx plugin) seems to be the best option. For example, I want to map an array, coming from the env variables, in order to display all values. However, it is impossible to get access to any variables.

ex (in my mdx file): <div>{process.env.MyVariable.map(el=>(<div>{el}</div>))}</div>

error: ReferenceError: process is not defined

I started to add Gatsby plugin env variables on this tutorial. I double checked how to do it with this sandbox. I can access to my variables inside my .js files, but not in my .mdx files.

What I am missing? Is it the best option to do it right?

Thanks for your help,

like image 303
Fabien Avatar asked Sep 07 '25 09:09

Fabien


1 Answers

.env variables are strings so, you can't loop them and display what's inside each position like an array. You can set something like this in your .env.development:

MESSAGES="message1, messages2, messages"

However, this would be one single string. You'll need to split them into a 3 position array by let dotEnvArray = process.env.MESSAGES.split(',').

If you use try: MESSAGES=["message1", "messages2", "messages3"] it will be treated as MESSAGES= "['message1', 'message2', 'message3']".

What you are seeing here:

module.exports = {
  plugins: [
    {
      resolve: `gatsby-plugin-env-variables`,
      options: {
        whitelist: ["MY_VAR", "MY_OTHER_VAR"]
      },
    },
  ],
}

Is an array of .env variables isolated. According to this plugin's documentation:

This will make MY_VAR & MY_OTHER_VAR available at runtime in your app by accessing process.env.MY_VAR or process.env.MY_OTHER_VAR.

However, those variables haven't any value defined, you will need to set them in your .env.development file anyway. This is because Gatsby by default only exposes all variables prefixed with GATSBY_. Take a look to Gatsby documentation about .env files for further information.

Answering another part of your question, once you've set (in your gatsby-config.js:

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

By default, running gatsby develop Gatsby will take your .env.development variables and will expose them under process.env.VAR_NAME, always isolated and treated as a single string, just how your CodeSandbox shows.

To achieve what you want in your repository, just add your environment variables in your whitelist.

module.exports = {
  plugins: [
    {
      resolve: `gatsby-plugin-env-variables`,
      options: {
        whitelist: ["ENDPOINTS"]
      },
    },
  ],
}
like image 172
Ferran Buireu Avatar answered Sep 10 '25 07:09

Ferran Buireu