Setup Guide

Run your own copy of the sync, in your own Google account.

This guide takes you from a fresh clone of the repository to a working sync. Everything runs under your account: your Cloud project, your Apps Script project, your OAuth client. Nothing is shared with the original author. Plan on about 30–45 minutes.

Why a Cloud project? The code runs in Apps Script, but Apps Script's built-in hidden project can't turn on the Google Health API. So the script is linked to a Cloud project you own. That project needs a consent screen, which is only a private record here: you are its only user. It's not a published app.

1. Before you start

ValueWhere it comes fromSecret?
PROJECT_NUMBERCloud project, step 3.6No
SCRIPT_IDApps Script project, step 4.3No
CLIENT_ID / CLIENT_SECRETOAuth client, step 6.1The secret is. Keep it out of git and chat.

2. Get the code and tools

  1. Clone the repository and install the dev dependencies (editor type hints only):
    git clone https://github.com/Suyash-Naik/fitbit-calendar-sync.git
    cd fitbit-calendar-sync
    npm install
    npm test        # optional: unit tests for the formatting code
  2. Install clasp, Google's command-line tool for Apps Script:
    npm install -g @google/clasp

    Windows PowerShell says "clasp.ps1 cannot be loaded because running scripts is disabled"? Run once: Set-ExecutionPolicy -Scope CurrentUser RemoteSigned

  3. Turn on the Apps Script API for your account: script.google.com/home/usersettings → Google Apps Script API: On.
  4. Log in with the same Google account: clasp login. A browser window opens; approve it.

3. Google Cloud project

  1. Create the project. console.cloud.google.com → project selector → New project. Any name works, e.g. fitbit-sync.
  2. Enable the APIs. Do this before the consent screen, or the health scopes won't show up later.
    • APIs and services → Library → search Google Health API → Enable
    • Same for Google Calendar API
  3. Consent screen. APIs and services → OAuth consent screen (opens the Google Auth Platform) → Get started:
    • App name: a name that identifies you, e.g. Jane Doe Health-to-Calendar. Google rejects names that contain its brands (Fitbit, Google…) or that don't identify the publisher. Support email: your address
    • Audience: External (Internal is greyed out for personal Gmail)
    • Contact information: your address → agree → Create
  4. Scopes. Sidebar → Data Access → Add or remove scopes → scroll to Manually add scopes → paste:
    https://www.googleapis.com/auth/calendar
    https://www.googleapis.com/auth/googlehealth.sleep.readonly
    https://www.googleapis.com/auth/googlehealth.activity_and_fitness.readonly
    https://www.googleapis.com/auth/script.external_request
    https://www.googleapis.com/auth/script.scriptapp
    https://www.googleapis.com/auth/script.send_mail
    Add to table → Update → Save. "Sensitive" and "restricted" labels are expected.
  5. Test user. Sidebar → Audience → Test users → + Add users → your address → Save. Leave Publishing status on Testing.
  6. Copy the project number. Cloud overview → Dashboard → Project info → PROJECT_NUMBER. It's the all-digits one, not the project ID.

4. Apps Script project

  1. Create it. script.google.com → New project → rename it, e.g. to Health-to-Calendar.
  2. Link it to your Cloud project. ⚙ Project Settings → Google Cloud Platform (GCP) Project → Change project → paste PROJECT_NUMBER → Set project.

    "Consent screen not configured"? Finish steps 3.3–3.5 first.

  3. Copy the script ID. Same page → IDs → SCRIPT_ID.

5. Push the code

  1. In the repo, open .clasp.json and replace the scriptId with yours. It currently points at the original author's project, which you can't push to:
    {
      "scriptId": "SCRIPT_ID",
      "rootDir": "src"
    }
  2. Upload the code: clasp push. If it asks to overwrite the manifest, answer y.
  3. Reload the Apps Script editor tab. You should see auth.gs, main.gs, health.gs and the others.

6. OAuth client for the Health API

Why a second OAuth client? The Health API rejects Apps Script's built-in token (403 DISALLOWED_OAUTH_SCOPES), because that token also carries Calendar, UrlFetch and trigger scopes. So the script requests a separate, health-only token through its own client (src/auth.js).
  1. Create the client. Cloud console → APIs and services → Credentials → + Create credentials → OAuth client ID:
    • Application type: Web application
    • Authorised redirect URIs → + Add URI → exactly:
      https://script.google.com/macros/d/SCRIPT_ID/usercallback
    • Leave Authorised JavaScript origins empty → Create
    Copy CLIENT_ID and CLIENT_SECRET from the dialog.
  2. Store them in the script. Apps Script → ⚙ Project Settings → Script properties → Add script property:
    PropertyValue
    HEALTH_CLIENT_IDCLIENT_ID
    HEALTH_CLIENT_SECRETCLIENT_SECRET
    Save script properties. They live only in your Apps Script project, never in code or git.

7. Authorize and first sync

Functions ending in _ are private and hidden from the Run menu. If the Run button is greyed out, open a file that has public functions, like auth.gs or main.gs.

  1. Authorize Health. Open auth.gs → select authorizeHealth → Run.
    • The first run asks for the Apps Script permissions (Calendar, external requests, triggers, email). On "Google hasn't verified this app": Advanced → Go to your app name.
    • The Execution log prints the redirect URI (check it matches step 6.1) and a long https://accounts.google.com/… URL. Open that URL, pick your account, tick both health permissions → Continue.
    • You land on "✅ Google Health authorized". Close the tab.
  2. Dry run. main.gs → syncDryRun → Run. The log lists every event it would create; nothing is written.
  3. Real sync. syncAll → Run. This creates the Fitbit calendar and its events. Check Google Calendar.
  4. Check for duplicates. Run syncAll again. The log should show "created":0, everything unchanged.
  5. Schedule it. installTrigger → Run. It now syncs every 4 hours (see ⏰ Triggers in the sidebar).
  6. Optional: backfill30 → Run, to fill in the last 30 days.
FunctionWhat it does
authorizeHealthLogs the link for the Health consent. Re-run when authorization expires
syncDryRunLogs the events it would create, no calendar changes
syncAllThe real sync; the trigger calls this
installTrigger / uninstallTriggerStart / stop the 4-hourly sync
backfill30Sync the last 30 days once
wipeSyncedEventsDelete every event this script created, and nothing else
resetHealthAuthForget the stored Health tokens
debugSchema / debugWorkoutTypesShow data structure and workout types without personal values

8. Settings

All optional, under Project Settings → Script properties. No code change or push needed; the next run picks them up.

PropertyDefaultMeaning
CALENDAR_NAMEFitbitTarget calendar, created automatically
LOOKBACK_DAYS2Days re-checked on each run
INCLUDE_NAPStrueSync non-main sleep sessions
MIN_WORKOUT_MINUTES0Skip shorter workouts, e.g. 15 hides short auto-detected walks
EXCLUDE_TYPESemptyComma-separated types, e.g. WALKING
WORKOUT_COLOR_ID10Event colour for workouts; empty for the calendar colour
ALERT_EMAILyour addressWhere failure alerts go, at most one per 12 h

9. Optional: stop the 7-day re-authorization

While the consent screen is in Testing, Google expires the Health authorization every 7 days. The script emails you when that happens; re-running authorizeHealth fixes it. To remove the limit, publish the consent screen to In production. Google first requires a home page, privacy policy and terms of service on a domain you control.

  1. Host your own pages. The site/ folder holds this website, and .github/workflows/pages.yml deploys it to GitHub Pages.
    • Edit site/privacy.html, site/terms.html and the footers so they name you, not the original author.
    • Push to your own GitHub repo (public, on a free plan) → Settings → Pages → Source: GitHub Actions.
    • Your pages are at https://username.github.io/repo/, plus privacy.html and terms.html.
  2. Branding. Google Auth Platform → Branding: fill in the three URLs, and under Authorised domains add username.github.io (no https://, no path). Don't upload a logo; that forces full verification. Save.
  3. Publish. Audience → Publish app. Unverified apps are allowed up to 100 users, and you are one. You'll see the unverified app screen when authorizing; continue via Advanced.

If Google blocks publishing outright for the restricted health scopes, switch back to Testing and live with the weekly re-authorization.

10. Troubleshooting

SymptomFix
Health scopes missing from the Data Access listEnable the Google Health API (3.2), then use Manually add scopes
"Change project" fails in Apps ScriptUse the project number, not the ID, and finish the consent screen first
clasp push: "User has not enabled the Apps Script API"Turn it on at script.google.com/home/usersettings (2.3)
clasp push: permission or "not found" error.clasp.json still has the original scriptId; use yours (5.1)
Run button greyed out / "No functions"The open file has only private _ functions. Open auth.gs or main.gs
redirect_uri_mismatchThe redirect URI on the OAuth client must exactly match the one authorizeHealth logs
403 PERMISSION_DENIED from health.googleapis.comAPI not enabled, scope missing from Data Access, you're not a test user, or a health box was left unticked. Run resetHealthAuth, then authorizeHealth
invalid_grant / "authorization expired"The 7-day Testing expiry. Run authorizeHealth again, or see step 9
"Missing script properties HEALTH_CLIENT_ID / HEALTH_CLIENT_SECRET"Add both client properties (6.2)
View on GitHub Back to top