This sample demonstrates how to sync new data written to a Firebase database to a Google Sheet. It includes a method for obtaining, storing, and using Oauth2 tokens for Google API access.
This code is also described in this blog post.
See file functions/index.js for the Google Sheet sync code.
Use the HTTPS function authGoogleAPI to request Oauth2 tokens for the Google API.
The trigger function is appendRecordToSpreadsheet.
To test it out, use the HTTPS function testSheetWrite.
The function triggers on when data is added to the DATA_PATH of the active Firebase database. In this sample, objects written to DATA_PATH/{ID} in the form {firstColumn: value, secondColumn: value, thirdColumn: value} are appended to the sheet.
To deploy and test the sample:
- Create a Firebase project on the Firebase Console and visit the Storage tab.
- Clone this repo:
git clone https://github.com/firebase/functions-samples. - Open this sample's directory:
cd functions-samples/google-sheet-sync - Setup your project by running
firebase use --addand select the project you had created. - Install dependencies in the functions directory:
cd functions; npm install; cd - - Using the Google APIs Console create an OAuth Client ID Click this link, select your project and then choose Web Application. In Authorized redirect URIs, you’ll need to enter
https://{YOUR-PROJECT-ID}.firebaseapp.com/oauthcallback. - Configure your Google API client ID and secret by running:
firebase functions:secrets:set GOOGLEAPI_CLIENT_ID firebase functions:secrets:set GOOGLEAPI_CLIENT_SECRET
- Create a new Google Sheet, and copy the long string in the middle of the Sheet URL. This is the Spreadsheet ID.
- Configure your Google Spreadsheet ID by running:
Add the following configuration to your `.env` file:
GOOGLEAPI_SHEET_ID="YOUR_SPREADSHEET_ID" WATCHEDPATHS_DATA_PATH="THE_DATA_PATH_YOU_WANT"
```
1. Deploy your project using `firebase deploy`
1. Configure the app once by opening the following URL and going through the auth flow `https://{YOUR-PROJET-ID}.firebaseapp.com/authgoogleapi`
1. To test, go to `{YOUR_PROJET_ID}.firebaseapp.com/testsheetwrite`. This will automatically add some test data in your Firebase Realtime Database in the data path that you set in `watchedpaths.data_path`.
1. Check your Google Sheet, to see these same values which have been appended via the trigger function.