Solving Environment Variable Issues in VSCode

While working on a WordPress-based headless CMS with Next.js for a client, I encountered a challenging issue with environment variables in VSCode that prevented me from fixing an issue where social media icons were not displaying.

The main challenge arose when updates made to the local database (managed by Local by Flywheel for WordPress and Next.js in my project folder) did not reflect on the local Next.js site. I initially suspected that the .env file was incorrectly pointing to the development site instead of my local setup. Despite correcting the GraphQL endpoint in both my .env and .env.local files, the issue persisted, prompting me to delete these files. Surprisingly, the build still succeeded.

Perplexed, I decided to start over: I deleted the project, re-cloned it from my private repository, installed the dependencies with npm install, and executed npm run build. Yet, the issue remained unresolved.

Have you tried turn it off and on again?

After taking a short break and drawing inspiration from the "IT Crowd" and Roy's famous advice, "Have you tried turning it off and on again?" I attempted to restart VSCode, but unfortunately, it made no difference.

The breakthrough occurred when I hardcoded the GraphQL URL in the ApolloClient configuration, resolving the issue. This revealed that the variables were sourced from somewhere other than my .env file, but the exact location—whether VSCode's cache or another part of the system—was unclear. A further investigation using the printenv command showed that these variables were visible within VSCode but not in the system terminal, shedding light on the situation. This indicated that VSCode was indeed overriding the variables defined in my .env files.

To resolve this, I used the unset VARIABLE_NAME command to remove the cached variables, allowing my .env.local file settings to be recognized properly. This step was crucial for me to proceed with the necessary site fixes.

If you encounter similar issues with environment variables in VSCode, consider clearing them with unset. I'm still looking into how these variables are retained in VSCode and how to prevent this behaviour in the future. If you have any insights or solutions, please share them in the comments.

Happy coding! Let's keep solving these puzzles one step at a time.

Avatar for Patrick Hladun

Written by Patrick Hladun

I'm a Frontend Developer and WordPress enthusiast on a mission to constantly improve my skills and keep up with the latest technology trends.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.