As someone relatively new to the front-end stack, I occasionally find myself stumbling into what might seem like "rookie" mistakes. Take, for instance, my recent attempt to access environment settings on the client side within a NextJS/React application. Thankfully, I'm fortunate to be surrounded by seasoned front-end developers, particularly Erwin Smit, who lend their expertise whenever I hit a snag. Shoutout to Erwin for the invaluable assistance!
In my quest to transition a client-side component into a server-side one using getServerSideProps, I encountered yet another hurdle. Despite my initial efforts, I found myself at a loss. The idea of setting up a separate API solely to fetch these settings seemed like overkill. However, my colleague came to the rescue, revealing a neat solution. It turns out that Next.js offers a convenient feature allowing environment variables to be seamlessly integrated into client-side applications. All it takes is prefixing your environment variable with "NEXT_PUBLIC_". For detailed instructions, refer to the documentation on the Vercel website.
It's crucial to bear in mind that when you make environment variables public, they become part of the JavaScript output during the next build. Any modifications to these variables will only take effect after a fresh build. Additionally, exercise caution to ensure that only non-sensitive information is made public—never share private keys or confidential data in this manner.
Until next time!