DEV Community

Cover image for What I Learned This Week: Hiding Keys in React.js (Or Not)

What I Learned This Week: Hiding Keys in React.js (Or Not)

Desiree Lerma
Software Engineer. Learning something new everyday!
・2 min read

This week I continued with mapping out my WatchNext project that I wrote about last week. I knew I wanted to create (or at least attempt to) a frontend only application to cement my current knowledge as well as learn more about React.js. Well, I quickly came across a bit of an obstacle. The API I plan on using requires a key to access the data. Now, I know in backend development you could simply create a .env file and add it to your .gitignore to hide any secrets or keys you don't want revealed to the user. (Incase, you're wondering what .gitignore does, it does what it sounds like. It tells version control to "ignore" the files added to it). I figured this would be the way to go with my frontend app as well. However, I was very suspicious. I thought, this is too easy to be the correct way to do it.

This lead me down a mini rabbit hole of research regarding how to properly hide/store secrets and keys in the frontend. Long story short, you can't. At least not if you plan on deploying your app at all in the future.

From my search, I learned a couple of things that I thought I would share here. I am still learning (as we all are) so I may expand on these points in another blog.

  • NOTHING is safe in .env on the frontend (even if you add it to .gitignore). This is because after deploy your app, the key can be seen in dev tools within the Network tab.

  • The safest bet is to make a backend to proxy API requests and store the keys there so they don't become exposed to a user.

  • Serverless functions can be implemented for a bit less work than creating an entire backend.

It was also suggested to me to use Next.js, a React framework that, as stated by the documentation, does/provides the following(and MORE):

  • A page-based routing system
  • API routes to build API endpoints with Serverless Functions (now we're speaking my language!)
  • Client-side routing with optimized prefetching

This sounds like it is just what I need! As I stated previously, as I dive deeper, I may write a more in depth blog to share what I learned and my experience with Next.js. For now, I hope you learned something a little new here!

Special thanks to Nicholas Papadakis, Ashlee Boyer, Chris Powell and Matthew Curtis for the tips, suggestions and advice!

Discussion (0)