reactjsbuild.env

Security of .env in React


I have a .env file that contains confidential keys, and I have a few questions for which I couldn't find a clear answer.

For example, let's consider a situation where we save a JWT token received from the server to the client's local storage, but before doing so, we encode it using a secret word stored in the environment. And when we retrieve it, we decode it using the same word.

So, how can I protect this secret word from prying eyes? Is it possible to somehow make the build still take the data from the server environment? Or are there any other methods?


Solution

  • Environment variables specified in a .env file will be embedded in the JavaScript bundle if you are using Create React App (CRA) and running the command npm run build. This is because CRA uses Webpack to bundle all the necessary files for the production build, including the environment variables.

    If environment variables containing confidential information such as API keys are embedded in the JavaScript bundle, it is possible for malicious actors to retrieve these variables by inspecting the JavaScript code.

    To prevent this, it is generally recommended to avoid embedding confidential information in client-side JavaScript code. Instead, you can use server-side technologies such as Node.js or a serverless platform like AWS Lambda to retrieve the confidential data and securely pass it to the client-side code when needed. Alternatively, you can use a technique called "tokenization," which involves replacing the actual API keys with temporary access tokens that have limited scope and lifetime.

    In summary, it is generally best to avoid embedding confidential information in client-side JavaScript code where possible, and instead, use server-side technologies or tokenization techniques to securely handle sensitive data.