Reputation: 1045
I want to keep keys and secrets from showing up to the end-user in the React app final build. I found ways suggesting to keep secrets in the environment variable file in docker.
Below is the code so far which is not working. The REACT_APP_SOME_API
is not accessible in React also I am not sure if using this method, secrets will be visible in the final build which I don't want.
Package.json in React:-
"scripts": {
"start": "rm -rf dist && webpack-dev-server --mode development --open --hot --port 8090",
"docker": "rm -rf dist && webpack --mode production && make docker-run",
"docker-push": "rm -rf dist && webpack --mode production && make docker-push --"
},
Makefile:-
docker:
docker build -t app .
docker-run: docker
docker run -it --env-file ./config.env -p "80:80" app
docker-push: TAG ?= latest
docker-push: docker
docker tag $(NAME) $(DOCKER_REPO):$(TAG)
docker push $(DOCKER_REPO):$(TAG)
config.env:-
REACT_APP_SOME_API=This-should-be-accessible-in-react-app
App.js in React app:-
return(
<>{process.env.REACT_APP_SOME_API}< />//This outputs undefined if console.log
);
Upvotes: 1
Views: 8045
Reputation: 1269
You should never put an API Key inside a client app in the first place. API keys are meant for server to server communication. If there are some secrets, you can store it inside session storage when the user logs in as a token.
Upvotes: 7
Reputation: 149
Create files for different environment like this inside your source directory like this:
Inside your environment file define different Key like:
REACT_APP_SOME_API="http://test.com"
Run the command to read keys from different file at the time of running:
"start": "sh -ac '. $(pwd)/env.development; rm -rf dist && webpack-dev-server --mode development --open --hot --port 8090'"
You can access the keys inside your application by
process.env.REACT_APP_SOME_API
Hope it helps.
Upvotes: 0
Reputation: 976
If something is utilized by your react application, it can always be accessed by the end-user. Even when talking about programs compiled to assembly, they can still be decompiled.
As a rule of thumb, do not expose API keys which are not supposed to be exposed to the end-users.
Upvotes: 1
Reputation: 2744
as in React documentation React apps have no hidden code.You have to write a backend for it (where all hidden parts are) which provides public interface your React app can query. You can try to obfuscate the code, but you cannot hide it.
That's the reason why some API's require you to also provide a domain for it so it provides another layer of limit about where people can use your API key at, even when published.
Upvotes: 3