Deep YT Data infrastructure & setup

A field guide to the Cloudflare runtime, Google OAuth boundary, remote-function data path, D1 persistence, and the commands that take the dashboard from a fresh clone to production.

Runtime
1 Worker
SvelteKit + static assets
Persistence
1 D1
Accounts, tokens, sessions
Server queries
2
Viewer + dashboard
Google scopes
Read only
YouTube + Analytics
Read-only by design

The application requests no channel-management scopes. It can read channel metadata and private analytics, but it cannot upload, edit, or delete YouTube content.

System topology

Cloudflare Workers is the single application runtime. SvelteKit serves the user interface and server endpoints, while Workers Static Assets serves the generated client assets. The Worker reaches D1 for durable identity state and Google for OAuth and YouTube data.

Deep YT Data system topology A browser connects to a Cloudflare Worker containing SvelteKit, remote functions, authentication routes, and static assets. The Worker connects to D1, Google OAuth, the YouTube Data API, and the YouTube Analytics API. Browser Svelte 5 UI CLOUDFLARE WORKER SvelteKit + Static Assets Remote queries viewer · dashboard Auth routes start · callback · logout Web Crypto + request hooks Cloudflare D1 accounts · sessions Google OAuth YouTube Data API channel + video metadata YouTube Analytics private performance reports
Runtime component map
LayerImplementationResponsibility
UISvelte 5 + Tailwind CSS 4Responsive dashboard, date selection, loading and error states
ServerSvelteKit on WorkersRemote functions, OAuth endpoints, request-scoped session lookup
StorageCloudflare D1Accounts, encrypted OAuth tokens, channel IDs, hashed sessions
External dataYouTube Data API v3Owned-channel totals, titles, thumbnails, publication metadata
External analyticsYouTube Analytics API v2Summary metrics, daily views, and ranked video performance

Analytics request path

The dashboard no longer uses page load functions. Its two server boundaries live in src/routes/data.remote.ts: getViewer resolves the header identity, and getDashboard resolves the complete report.

Analytics remote-query sequence The browser calls the dashboard remote query. The Worker validates the dates, resolves the session from D1, obtains a valid Google token, requests YouTube channel data, fans out three analytics requests, and returns the typed result. Browser Remote query D1 + token layer YouTube APIs getDashboard(start, end) Valibot validation normalize date range hash cookie · resolve account account + encrypted token valid access token · owned channel parallel: summary · daily · top videos analytics rows + metadata typed dashboard result
  1. The browser derives the query input from the URL’s start and end parameters.
  2. The remote query validates the input with Valibot and captures the current request’s locals and Cloudflare platform bindings.
  3. The request hook has already resolved the opaque session cookie against its SHA-256 hash in D1.
  4. The account’s access token is decrypted. If it is within one minute of expiry, the refresh token is used and the new access token is encrypted back into D1.
  5. The Worker fetches the owned channel, then requests the summary, daily series, and top videos concurrently.
  6. Svelte renders the returned result. Changing the date parameters produces a distinct remote-query key.

OAuth, token protection & sessions

Google authentication uses the authorization-code flow with PKCE. A short-lived, HMAC-signed state cookie binds the callback to the initiating browser, while the long-lived application session remains independently revocable in D1.

Google OAuth and application-session lifecycle The browser starts OAuth at the Worker. The Worker creates signed state and a PKCE challenge, redirects to Google, verifies the callback, exchanges the code, encrypts tokens in D1, and gives the browser an opaque session cookie whose hash is stored in D1. Browser HttpOnly cookies Worker auth routes PKCE S256 HMAC state verification AES-GCM token encryption Google OAuth consent + token exchange Cloudflare D1 encrypted tokens + session hash 1 · /auth/google 2 · challenge + state 3 · code callback 4 · persist identity 5 · opaque session cookie
Security control map
Asset or threatControlLifetime / behavior
Authorization-code interceptionPKCE with S256 challengeVerifier exists only in the signed OAuth state cookie
Callback forgery / CSRFHMAC-SHA-256 state cookie and returned-state comparison10 minutes
Google access + refresh tokensAES-GCM encryption before D1 persistenceAccess token refreshed when near expiry
Application sessionOpaque random token in HttpOnly SameSite=Lax cookie; only SHA-256 hash stored30 days, revocable by deleting the D1 row
Redirect abuseReturn path must begin with one slash and not twoInvalid values fall back to /
Secret exposureWrangler secrets / local .dev.varsNever committed or placed in wrangler.jsonc

D1 data model

The initial migration creates only two tables. The deliberately small schema makes revocation and account cleanup straightforward: deleting an account cascades to every session.

Persistent records
TableKey fieldsPurpose
accountsid, unique google_sub, profile fields, channel_id, encrypted access/refresh tokens, expiry, scopesOne durable identity and Google authorization record per Google subject
sessionstoken_hash, account_id, expires_at, created_atRevocable application sessions without persisting the bearer token itself

Indexes cover session lookup by account and expiry. The foreign key uses ON DELETE CASCADE.

Local setup

1. Prepare Google Cloud

  1. Create or select a Google Cloud project.
  2. Enable YouTube Data API v3 and YouTube Analytics API.
  3. Configure the OAuth consent screen. While publishing status is Testing, add each Google account that should be allowed to sign in as a test user.
  4. Create an OAuth 2.0 Client ID of type Web application.
  5. Add http://localhost:5173/auth/google/callback as an authorized redirect URI.

2. Install and configure the project

pnpm install
cp .dev.vars.example .dev.vars

Fill .dev.vars locally with four values:

GOOGLE_CLIENT_ID
The Google web OAuth client ID
GOOGLE_CLIENT_SECRET
The corresponding Google client secret
TOKEN_ENCRYPTION_KEY
A long random value used to protect persisted Google tokens
SESSION_SECRET
A different long random value used to sign OAuth state

3. Generate bindings and migrate local D1

pnpm gen
pnpm db:migrate:local
pnpm dev

pnpm gen refreshes the typed Cloudflare environment. The migration command applies migrations/0001_initial.sql to Wrangler’s local D1 database. The Vite development server then runs the app at http://localhost:5173.

Production rollout

The Wrangler configuration declares a D1 binding named DB, four required secrets, Workers Static Assets, observability, the nodejs_compat compatibility flag, a Workers.dev route, and preview URLs.

Before the first deploy

Add the deployed callback URL—https://YOUR-WORKER.YOUR-SUBDOMAIN.workers.dev/auth/google/callback—to the same Google OAuth client. The string must match exactly.

First deployment

pnpm exec wrangler deploy --secrets-file .dev.vars
pnpm db:migrate:remote

Automatic provisioning creates the declared D1 database and writes generated resource details back to wrangler.jsonc. The production migration is applied after that database exists.

Later deployments

pnpm deploy

Rotate a secret

pnpm exec wrangler secret put NAME

Enter the value only at Wrangler’s interactive prompt. Do not include a secret in a shell argument, source file, or Wrangler configuration.

Declared Cloudflare behavior
CapabilityConfiguration
Application entry.svelte-kit/cloudflare/_worker.js
Static assetsASSETS binding from .svelte-kit/cloudflare
DatabaseD1 binding DB
LogsObservability enabled; head sampling rate 1.0
TracesEnabled; head sampling rate 0.1
AccessWorkers.dev and preview URLs enabled

Operations & validation

Repository quality gate

pnpm format
pnpm check
pnpm lint
pnpm test

The test suite runs with Cloudflare’s Workers Vitest pool, provisions an isolated local D1 binding, and applies the real migration before each Workers-runtime test group.

Failure behavior worth knowing

  • A missing or expired application session returns the disconnected landing state rather than attempting a Google request.
  • An expired Google access token is refreshed automatically when a refresh token is available.
  • A reversed date range returns a typed user-facing error before any YouTube analytics request.
  • A Google 403 produces guidance to confirm both APIs and approved scopes.
  • Server failures are logged as structured JSON without logging token values.
Public API coverage is not YouTube Studio parity

The Analytics API exposes views, watch time, average duration, average percentage viewed, subscriber movement, and engagement. It does not guarantee every card available in YouTube Studio; do not assume impressions or click-through rate are available.