How Do You Hide API key in Static Site?

I’m a new developer and I wanted to deploy a single-page React application to Render. I created the application using Create React App and I have an API key and backend URL that I want to keep hidden. When I tried to deploy this as a Static Site, I set up two environment variables but these did not get included in my static site.

I think this happened because I didn’t include them in my Build Command (see below). Is this how I would include two environmental variables?

Build Command: REACT_APP_API_KEY= $MY_ENV1 REACT_APP_BASE_URL=$MY_ENV2 yarn build
Publish Directory: build

If I did this, though, the API key could still be found in the code. Right? So how do you keep it hidden for a Static Site like this? What is best practice?

According to React documentation, there’s no way to hide your secrets in a static React app.

If you want to “keep secrets”, you’ll need to create a backend application that also loads your React frontend. You can find a sample tutorial that does that with Node and Express, with sample deploy config for Render!

You can access your local and Render environment variables in backend code using process.env.[VARIABLE], e.g process.env.API_KEY.

Not sure why you want to keep your backend URL (APP_BASE_URL) secret, but using the strategy in the tutorial above, you can surely do that because it becomes as simple as calling a relative URL (like /api/whatever from the React frontend, thereby not revealing the base URL.

1 Like

Hey,

As ‘Bayode’ said. Using a static site to deploy your React application is a good approach but static files aren’t aware of the environment they’ve been deployed on since they live and are served on the browser.

So, you’ll need to bundle them via Webpack for example. As recommended by ‘Bayode’.

See https://trekinbami.medium.com/using-environment-variables-in-react-6b0a99d83cf5.

Jérémy.
Render Support, UTC+3

1 Like

That tutorial looks excellent. I’m new to development so I thought it was best practice to hide your back end API, but apparently not! So much to learn.

Hey Mark,

Certainly, you can provision your secrets within the environment your backend API resides in. However, when it comes to static sites, they exist within the browser environment, which lacks the setup you have locally or through a cloud hosting provider like us. Therefore, you’ll need to ‘bundle’ your client-side environment variables within your build so they can be used in your static files.

Jérémy.
Render Support, UTC+3

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.