Skip to main content

Google Drive Integration

Add Google Drive as a Layer 2 backup to your synchronization strategy. This provides a failsafe backup mechanism that complements the fast Cloudflare edge sync.
Google Drive sync serves as an additional safety net. It’s slower than Cloudflare (3-5 seconds) but provides excellent long-term backup reliability.

Prerequisites

  • Google account
  • Google Cloud Console access
  • Estudo Organizado already set up (local or deployed)

Setup Google Drive API

1

Create Google Cloud Project

  1. Go to Google Cloud Console
  2. Create a new project or select an existing one
  3. Name it something like “Estudo Organizado”
2

Enable Drive API

  1. In the Cloud Console, go to APIs & ServicesLibrary
  2. Search for “Google Drive API”
  3. Click on it and press Enable
3

Configure OAuth Consent Screen

  1. Go to APIs & ServicesOAuth consent screen
  2. Select External user type
  3. Fill in:
    • App name: Estudo Organizado
    • User support email: Your email
    • Developer contact: Your email
  4. Click Save and Continue
  5. Skip scopes (click Save and Continue)
  6. Add yourself as a test user
  7. Click Save and Continue
4

Create OAuth Client ID

  1. Go to APIs & ServicesCredentials
  2. Click + Create CredentialsOAuth client ID
  3. Application type: Web application
  4. Name: “Estudo Organizado Web Client”
  5. Authorized JavaScript origins: Add your domain(s)
    • http://localhost:8000 (for local testing)
    • https://estudo-organizado.pages.dev (your Cloudflare URL)
  6. Authorized redirect URIs: Same as origins
  7. Click Create
5

Copy Client ID

After creation, copy your Client ID. It looks like:
123456789-abcdefghijklmnop.apps.googleusercontent.com
Keep this Client ID safe - you’ll need it to configure the app.

Configure in Application

1

Open Settings

In Estudo Organizado, click the ⚙️ Settings icon
2

Enter Client ID

  1. Find the Google Drive section
  2. Paste your Client ID into the input field
  3. The page will reload to initialize the Google APIs
3

Connect to Drive

  1. Click the Connect button
  2. A Google OAuth popup will appear
  3. Select your Google account
  4. Grant permission to access Drive files
4

Verify Connection

You should see:
  • Green dot indicator
  • “Connected to Google Drive” message
  • Last sync timestamp

How It Works

Initialization

The Drive module loads Google’s API libraries dynamically:
// From drive-sync.js:14-27
export function initGoogleAPIs() {
    const CLIENT_ID = localStorage.getItem('estudo_drive_client_id');
    if (!CLIENT_ID) return;

    // Load GAPI (Google API client)
    const scriptGapi = document.createElement('script');
    scriptGapi.src = 'https://apis.google.com/js/api.js';
    scriptGapi.onload = () => {
        gapi.load('client', () => {
            gapi.client.init({
                discoveryDocs: ['https://www.googleapis.com/discovery/v1/apis/drive/v3/rest']
            }).then(() => { gapiInited = true; });
        });
    };
    document.head.appendChild(scriptGapi);
}

File Storage

Your data is stored as a single JSON file named estudo-organizado-data.json in your Google Drive.

Sync Strategy

The system uses timestamp comparison to prevent data loss:
// From drive-sync.js:157-171
if (driveData.lastSync && state.lastSync && 
    new Date(driveData.lastSync) > new Date(state.lastSync)) {
    // Drive has newer version
    showConfirm(
        'Found newer version in Drive. Overwrite local data?',
        () => {
            setState(driveData);
            saveStateToDB().then(() => {
                showToast('Data updated from Drive!', 'success');
            });
        }
    );
}
If Drive has a newer version (e.g., from another device), you’ll be asked before overwriting local data.

Automatic Sync

Once connected, Drive automatically syncs with a 10-second debounce:
// From drive-sync.js:256-264
document.addEventListener('stateSaved', () => {
    if (gapi.client?.getToken() !== null && state.driveFileId) {
        // Debounce to prevent sync overload
        if (window.driveSyncTimeout) clearTimeout(window.driveSyncTimeout);
        window.driveSyncTimeout = setTimeout(() => {
            SyncQueue.add(() => syncWithDrive());
        }, 10000); // 10s debounce
    }
});

Upload Process

The system uses Google Drive’s multipart upload API:
// From drive-sync.js:187-209
state.lastSync = new Date().toISOString();
const accessToken = gapi.client.getToken().access_token;
const metadata = { 
    name: 'estudo-organizado-data.json', 
    mimeType: 'application/json' 
};

const boundary = '-------314159265358979323846';
const multipartRequestBody =
    delimiter +
    'Content-Type: application/json; charset=UTF-8\r\n\r\n' +
    JSON.stringify(metadata) +
    delimiter +
    'Content-Type: application/json\r\n\r\n' +
    JSON.stringify(state) +
    close_delim;

await fetch(
    `https://www.googleapis.com/upload/drive/v3/files/${state.driveFileId}?uploadType=multipart`,
    {
        method: 'PATCH',
        headers: {
            'Authorization': 'Bearer ' + accessToken,
            'Content-Type': 'multipart/related; boundary=' + boundary
        },
        body: multipartRequestBody
    }
);

UI Indicators

The app shows different status indicators:
// From drive-sync.js:56-81
if (status === 'connected') {
    sub.textContent = state.lastSync 
        ? `Synced: ${new Date(state.lastSync).toLocaleString('pt-BR')}` 
        : 'Synchronized';
    btn.textContent = 'Sync Now';
} else if (status === 'syncing') {
    sub.textContent = 'Syncing...';
    btn.textContent = 'Please wait...';
} else {
    sub.textContent = 'Click to connect';
    btn.textContent = 'Connect';
}

Disconnected

Gray dot - Not connected

Syncing

Yellow dot - Sync in progress

Connected

Green dot - Synced successfully

Manual Sync

You can manually trigger sync at any time:
  1. Open Settings (⚙️)
  2. Find the Google Drive section
  3. Click Sync Now
This is useful when:
  • You want to ensure latest data is backed up
  • You’re switching devices
  • You’ve made important changes

Disconnecting

To disconnect Google Drive:
1

Open Settings

Click the ⚙️ icon
2

Disconnect

Scroll to Google Drive section and click Disconnect
3

Confirm

The app will:
  • Revoke access token
  • Clear local Client ID
  • Remove Drive file reference
  • Update UI to disconnected state
Disconnecting does NOT delete your backup file from Drive. It only stops automatic syncing. Your data remains safe in Drive.

Troubleshooting

Your browser may be blocking popups:
  1. Look for popup blocker icon in address bar
  2. Allow popups from your domain
  3. Try clicking Connect again
The Google APIs failed to initialize:
  1. Check your internet connection
  2. Verify Client ID is correct
  3. Reload the page
  4. Check browser console for errors
Mobile Safari sometimes blocks cross-site cookies:
  1. Go to Settings → Safari
  2. Disable “Prevent Cross-Site Tracking”
  3. Try connecting again
  4. Alternatively, use Cloudflare sync (works better on mobile)
Drive sync is intentionally slower (3-5 seconds) than Cloudflare:
  1. This is normal behavior
  2. Use Cloudflare sync for real-time needs
  3. Use Drive as backup/secondary layer
  4. Reduce sync frequency by working longer between syncs
If you modify data on multiple devices simultaneously:
  1. The app will ask which version to keep
  2. Choose the device with the most recent changes
  3. Consider using Cloudflare sync for multi-device scenarios

Limitations

Be aware of these Drive sync limitations:
  1. Speed: 3-5 second latency per sync operation
  2. Mobile OAuth: iOS Safari may have CORS issues with OAuth popups
  3. File Size: Large datasets (multi-MB) will sync slower
  4. Quota: Google Drive API has daily quota limits (unlikely to hit with normal use)

Best Practices

1

Use Dual Sync

Enable both Cloudflare (fast) and Drive (reliable backup):
  • Cloudflare: Real-time sync (less than 150ms)
  • Drive: Background backup (10s debounce)
2

Regular Manual Syncs

Before important sessions or switching devices:
  1. Click “Sync Now” in Drive settings
  2. Wait for confirmation
  3. Switch devices knowing data is fresh
3

Monitor Sync Status

Check the status indicator regularly:
  • Green dot = Good to go
  • Yellow = Wait a moment
  • Gray = Not connected (re-connect if needed)

Comparison with Cloudflare Sync

FeatureCloudflareGoogle Drive
SpeedLess than 150ms3-5 seconds
LatencyUltra-lowModerate
MobileExcellentiOS Safari issues
SetupMore stepsSimpler OAuth
ReliabilityVery highVery high
Use caseReal-time syncBackup layer
For the best experience, use both sync methods: Cloudflare for speed and Drive for safety.

Next Steps

Cloudflare Setup

Set up ultra-fast edge sync with Cloudflare Workers

Manual Backup

Learn about local JSON export/import

Build docs developers (and LLMs) love