How to fix environment variables not working in Gatsby and Next JS
After some months of publishing my blog page, I decided to add some user interactivity (a like button). This means I will need to send and receive data from the backend.
That's the good news for me. The bad news is that Gatsby generates static contents, but the like button will require dynamic interactivity. Axios is the recommended man for this kind of job. But I got a resource fetching error when I added process.env.GATSBY_STRAPI
to my axios.get
function. Though, process.env.GATSBY_STRAPI
works well in my gatsby-config.js
file.
Obviously, every other file in my project is not recognizing the .env
file. apart from the gatsby-config.js
file.
How to fix this error?
- Open up your terminal and
cd
to your project root directory. Then runnpm install dotenv
- Require the
dotenv
in yourgatsby-config.js
file, make sure it's at the top
require("dotenv").config();
module.exports = {};
I have also experienced this issue in my Next JS projects, so you can use this same process to fix the error in Next JS
Now you can use your environment variables in all your files. Hope this helps.
Don't forget to hit the like button, follow me on socials and also share this post to your timeline… Gracias 😎
Tags: