Hide API Key in Knitted HTML?

I'm knitting a series of HTML reports for public use. Not self-contained. I'm seeing the API key (googleway package) is embedded inside the HTML document, but it's my understanding that this is not very secure. Is there a solution/alternative to this? One idea I had was editing the HTML where the key is kept. Change from
<script src=" https://maps.googleapis.com/maps/api/js?key=xxx&libraries=visualization,geometry,places,drawing "></script>
to
<script src="map_key.js">

Saving the api key file locally. But I don't want to edit every single file. Another idea is to write an R script to edit HTML?

It seems like this is hard coded into the googleway package

So you should open an issue with them to see if they have advice. rmarkdown itself does not have ways of controlling how googleway behave.

If there is a more secure way, this should definitely be improved on their side.

You could for sure do a post processing using xml2 package for example to detect and change this.

I'll do that, open an issue. I was able to write a small script using xml2. I suppose that is the best solution for now! Here's my solution if others have trouble. I saved the js file that the API called into api.js.

library(xml2)

files = list.files(pattern = ".html")

replace_api_key <- function(html_filename) {
  h2 = read_html(html_filename)
  
  # Find api key
  g_api <- xml_find_first(h2, "//script[contains(@src, 'maps.googleapis.com')]")
  xml_attrs(g_api) <- c(src = 'lib/api.js')
  
  write_html(h2, html_filename,
             options = c("as_html"))
}
1 Like

Great !
Maybe you should using xml_find_first And XPATH so that it does not break in the future if position changes. XPATH is not easy at first but it is useful !

Appreciate it, I'll try that - I know this line isn't great code. EDIT: Code now changed.

1 Like