rshinygoogle-sheets-apigooglesheets4

Connect to googlesheets via shiny in R with googlesheets4


I'm trying to use an updated version of this example to connect to a private googlesheet via shiny, and deploy this app on the shinyapps.io server. The user is not required to authenticate to a google account as the app uses a specified pre-existing googlesheet.

I've followed this example (partly copied here), attempting to save the token to my shiny app:

# previous googlesheets package version:
shiny_token <- gs_auth() # authenticate w/ your desired Google identity here
saveRDS(shiny_token, "shiny_app_token.rds")

but tried to update it to googlesheets4, like this:

ss <- gs4_get("MY GOOGLE DOC URL") # do the authentication once, manually.
ss
gs4_has_token() # check that the token exists

# get token
ss_token <- gs4_token()
# save the token
save(ss_token, file = "APP PATH ... /data/tk.rdata")

Then in the app, I have placed this code outside the shinyApp() function.

load("data/tk.rdata")

googlesheets4::gs4_auth(token = ss_token, use_oob = T)

In the app, I connect to a google doc from the app, using a hardcoded id obtained from ss$spreadsheet_id above. The app works locally.

After attempting to deploy the app to the server I get the error "...Can't get google credentials. Are you running googlesheets4 in a non-interactive session?... etc" I thought that the token would contain sufficient information for this.

I'd be grateful if anyone can point me to a guide to setting this up, and also comment on whether this approach (saving a token on the shinyapps.io) is safe?

I've looked at other examples, but it seems most are for the previous version of googlesheets


Solution

  • Just follow the instructions in this link:

    # designate project-specific cache
    options(gargle_oauth_cache = ".secrets")
    # check the value of the option, if you like
    gargle::gargle_oauth_cache()
    # trigger auth on purpose to store a token in the specified cache
    # a broswer will be opened
    googlesheets4::sheets_auth()
    # see your token file in the cache, if you like
    list.files(".secrets/")
    # sheets reauth with specified token and email address
    sheets_auth(
     cache = ".secrets",
     email = "youremail"
     )