I develop a small front end using Angular that reference Google Map. The GMap documentation says that I must add a reference in my index.html page withe the API key:
<script type="text/javascript" src="https://maps.google.com/maps/api/js?key=API_KEY" async defer></script>
Since this project is on GitHub, the API key becomes public to everyone. How can I protect it?
In Angular, there is an envrionment.ts file (with production equivalent) where I store sensitive info such as key, but how I can inject the API key by code?
You could create a file called environment.ts.dist
which is your environment.ts
file but without your personal API key - replace it with a comment or dummy value (other sensible information as well). Someone copying the project will see how the file should look like and can insert their own API key after just renaming the file. Your environment.ts
should then be added to .gitignore
so that it's never in the repository.
Environment variables can be accessed like this
import {environment} from "../environments/environment";
...
let apiKey: string = environment.apiKey; // or whatever your variable is named instead of "apiKey"
You should remember - as says in the post linked by @bugs - that an angular application can be reverse engineered and your key is not perfectly safe in your deployed application, but like this you can keep it from being pushed into git while still providing all the information someone might need using the project.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With