We have a Sitecore JSS server-side rendering mode, which uses Node.js and React.js as the tech stack. Unfortunately, the API key and API host are written in the JavaScript files. How can we avoid this?
2 Answers
This issue arises because the repository contains these details somewhere. Ensure that your scconfig.json or .env file does not contain the SITECORE_API_KEY and SITECORE_API_HOST.
By the way, why isn't this handled by default?
It's because, in client-side rendering mode, these details need to be written in JavaScript files. This behavior is necessary to support client-side rendering.
The React documentation provides a great summary:
Your project can consume variables declared in your environment as if they were declared locally in your JS files. By default you will have NODE_ENV defined for you, and any other environment variables starting with REACT_APP_.
WARNING: Do not store any secrets (such as private API keys) in your React app!
Environment variables are embedded into the build, meaning anyone can view them by inspecting your app's files.
The environment variables are embedded during the build time. Since Create React App produces a static HTML/CSS/JS bundle, it can’t possibly read them at runtime. To read them at runtime, you would need to load HTML into memory on the server and replace placeholders in runtime, as described here. Alternatively you can rebuild the app on the server anytime you change them.
Note: You must create custom environment variables beginning with REACT_APP_. Any other variables except NODE_ENV will be ignored to avoid accidentally exposing a private key on the machine that could have the same name. Changing any environment variables will require you to restart the development server if it is running.
These environment variables will be defined for you on process.env. For example, having an environment variable named REACT_APP_NOT_SECRET_CODE will be exposed in your JS as process.env.REACT_APP_NOT_SECRET_CODE.
Broadly speaking:
- Don't store secrets in source control.
- Do follow the framework best practices when dealing with environment configs and secrets.
- Do use a server-side proxy to handle API requests and to perform operations that use secrets.
Also keep in mind that different frameworks handle environment configurations and secrets slightly differently. For example, Next.js only publicly exposes environment secrets if they have a name prefix of NEXT_PUBLIC_
, or if your code (incorrectly) exposes those secrets to the client.