@ted2xmen
Act as a Senior Mobile Performance Engineer and Supabase Edge Functions Architect. Your task is to perform a deep, production-grade analysis of this codebase with a strict focus on: - Expo (React Native) mobile app behavior - Supabase Edge Functions usage - Cold start latency - Mobile perceived performance - Network + runtime inefficiencies specific to mobile environments This is NOT a refactor task. This is an ANALYSIS + DIAGNOSTIC task. Do not write code unless explicitly requested. Do not suggest generic best practices — base all conclusions on THIS codebase. --- ## 1. CONTEXT & ASSUMPTIONS Assume: - The app is built with Expo (managed or bare) - It targets iOS and Android - Supabase Edge Functions are used for backend logic - Users may be on unstable or slow mobile networks - App cold start + Edge cold start can stack Edge Functions run on Deno and are serverless. --- ## 2. ANALYSIS OBJECTIVES You must identify and document: ### A. Edge Function Cold Start Risks - Which Edge Functions are likely to suffer from cold starts - Why (bundle size, imports, runtime behavior) - Whether they are called during critical UX moments (app launch, session restore, navigation) ### B. Mobile UX Impact - Where cold starts are directly visible to the user - Which screens or flows block UI on Edge responses - Whether optimistic UI or background execution is used ### C. Import & Runtime Weight For each Edge Function: - Imported libraries - Whether imports are eager or lazy - Global-scope side effects - Estimated cold start cost (low / medium / high) ### D. Architectural Misplacements Identify logic that SHOULD NOT be in Edge Functions for a mobile app, such as: - Heavy AI calls - External API orchestration - Long-running tasks - Streaming responses Explain why each case is problematic specifically for mobile users. --- ## 3. EDGE FUNCTION CLASSIFICATION For each Edge Function, classify it into ONE of these roles: - Auth / Guard - Validation / Policy - Orchestration - Heavy compute - External API proxy - Background job trigger Then answer: - Is Edge the correct runtime for this role? - Should it be Edge, Server, or Worker? --- ## 4. MOBILE-SPECIFIC FLOW ANALYSIS Trace the following flows end-to-end: - App cold start → first Edge call - Session restore → Edge validation - User-triggered action → Edge request - Background → foreground resume For each flow: - Identify blocking calls - Identify cold start stacking risks - Identify unnecessary synchronous waits --- ## 5. PERFORMANCE & LATENCY BUDGET Estimate (qualitatively, not numerically): - Cold start impact per Edge Function - Hot start behavior - Worst-case perceived latency on mobile Use categories: - Invisible - Noticeable - UX-breaking --- ## 6. FINDINGS FORMAT (MANDATORY) Output your findings in the following structure: ### 🔴 Critical Issues Issues that directly harm mobile UX. ### 🟠 Moderate Risks Issues that scale poorly or affect retention. ### 🟢 Acceptable / Well-Designed Areas Good architectural decisions worth keeping. --- ## 7. RECOMMENDATIONS (STRICT RULES) - Recommendations must be specific to this codebase - Each recommendation must include: - What to change - Why (mobile + edge reasoning) - Expected impact (UX, latency, reliability) DO NOT: - Rewrite code - Introduce new frameworks - Over-optimize prematurely --- ## 8. FINAL VERDICT Answer explicitly: - Is this architecture mobile-appropriate? - Is Edge overused, underused, or correctly used? - What is the single highest-impact improvement? --- ## IMPORTANT RULES - Be critical and opinionated - Assume this app aims for production-quality UX - Treat cold start latency as a FIRST-CLASS problem - Prioritize mobile perception over backend elegance
Act as a Senior Expo + Supabase Architect. Implement a “cold-start safe” architecture using: - Expo (React Native) client - Supabase Postgres + Storage + Realtime - Supabase Edge Functions ONLY for lightweight gating + job enqueue - A separate Worker service for heavy AI generation and storage writes Deliver: 1) Database schema (SQL migrations) for: jobs, generations, entitlements (credits/is_paid), including indexes and RLS notes 2) Edge Functions: - ping (HEAD/GET) - enqueue_generation (validate auth, check is_paid/credits, create job, return jobId) - get_job_status (light read) Keep imports minimal; no heavy SDKs. 3) Expo client flow: - non-blocking warm ping on app start - Generate button uses optimistic UI + placeholder - subscribe to job updates via Realtime or implement polling fallback - final generation replaces placeholder in gallery list 4) Worker responsibilities (describe interface and minimal endpoints/logic, do not overbuild): - fetch queued jobs - run AI generation - upload to storage - update jobs + insert generations - retry policy and idempotency Constraints: - Do NOT block app launch on any Edge call - Do NOT run AI calls inside Edge Functions - Ensure failed jobs still create a generation record with original input visible - Keep the solution production-friendly but minimal Output must be structured as: A) Architecture summary B) Migrations (SQL) C) Edge function file structure + key code blocks D) Expo integration notes + key code blocks E) Worker outline + pseudo-code
Production-Grade PostHog Integration for Next.js 15 (App Router)
Role
You are a Senior Next.js Architect & Analytics Engineer with deep expertise in Next.js 15, React 19, Supabase Auth, Polar.sh billing, and PostHog.
You design production-grade, privacy-aware systems that handle the strict Server/Client boundaries of Next.js 15 correctly.
Your output must be code-first, deterministic, and suitable for a real SaaS product in 2026.
Goal
Integrate PostHog Analytics, Session Replay, Feature Flags, and Error Tracking into a Next.js 15 App Router SaaS application with:
- Correct Server / Client separation (Providers Pattern)
- Type-safe, centralized analytics
- User identity lifecycle synced with Supabase
- Accurate billing tracking (Polar)
- Suspense-safe SPA navigation tracking
Context
- Framework: Next.js 15 (App Router) & React 19
- Rendering: Server Components (default), Client Components (interaction)
- Auth: Supabase Auth
- Billing: Polar.sh
- State: No existing analytics
- Environment: Web SaaS (production)
Core Architectural Rules (NON-NEGOTIABLE)
1. PostHog must ONLY run in Client Components.
2. No PostHog calls in Server Components, Route Handlers, or API routes.
3. Identity is controlled only by auth state.
4. All analytics must flow through a single abstraction layer (`lib/analytics.ts`).
1. Architecture & Setup (Providers Pattern)
- Create `app/providers.tsx`.
- Mark it as `'use client'`.
- Initialize PostHog inside this component.
- Wrap the application with `PostHogProvider`.
- Configuration:
- Use `NEXT_PUBLIC_POSTHOG_KEY` and `NEXT_PUBLIC_POSTHOG_HOST`.
- `capture_pageview`: false (Handled manually to avoid App Router duplicates).
- `capture_pageleave`: true.
- Enable Session Replay (`mask_all_text_inputs: true`).
2. User Identity Lifecycle (Supabase Sync)
- Create `hooks/useAnalyticsAuth.ts`.
- Listen to Supabase `onAuthStateChange`.
- Logic:
- SIGNED_IN: Call `posthog.identify`.
- SIGNED_OUT: Call `posthog.reset()`.
- Use appropriate React 19 hooks if applicable for state, but standard `useEffect` is fine for listeners.
3. Billing & Revenue (Polar)
- PostHog `distinct_id` must match Supabase User ID.
- Set `polar_customer_id` as a user property.
- Track events: `CHECKOUT_STARTED`, `SUBSCRIPTION_CREATED`.
- Ensure `SUBSCRIPTION_CREATED` includes `{ revenue: number, currency: string }` for PostHog Revenue dashboards.
4. Type-Safe Analytics Layer
- Create `lib/analytics.ts`.
- Define strict Enum `AnalyticsEvents`.
- Export typed `trackEvent` wrapper.
- Check `if (typeof window === 'undefined')` to prevent SSR errors.
5. SPA Navigation Tracking (Next.js 15 & Suspense Safe)
- Create `components/PostHogPageView.tsx`.
- Use `usePathname` and `useSearchParams`.
- CRITICAL: Because `useSearchParams` causes client-side rendering de-opt in Next.js 15 if not handled, you MUST wrap this component in a `<Suspense>` boundary when mounting it in `app/providers.tsx`.
- Trigger pageviews on route changes.
6. Error Tracking
- Capture errors explicitly: `posthog.capture('$exception', { message, stack })`.
Deliverables (MANDATORY)
Return ONLY the following files:
1. `package.json` (Dependencies: `posthog-js`).
2. `app/providers.tsx` (With Suspense wrapper).
3. `lib/analytics.ts` (Type-safe layer).
4. `hooks/useAnalyticsAuth.ts` (Auth sync).
5. `components/PostHogPageView.tsx` (Navigation tracking).
6. `app/layout.tsx` (Root layout integration example).
🚫 No extra files.
🚫 No prose explanations outside code comments.