|
| 1 | +# POC T003: API Key Injection (Next.js) - Results |
| 2 | + |
| 3 | +## Verdict: VALIDATED |
| 4 | + |
| 5 | +The API key injection pattern from the Gatsby Docs site can be successfully replicated in Next.js 15 with App Router, with no hydration mismatches or significant session issues. |
| 6 | + |
| 7 | +## Evidence |
| 8 | + |
| 9 | +### 1. Session Cookie Handling |
| 10 | +- **Route Handler** (`/api/user`): Successfully reads cookies from incoming requests |
| 11 | +- **Rails API Integration**: Proxies requests to Rails `/api/me` and `/api/api_keys` endpoints |
| 12 | +- **Logged-out state**: Returns empty user data, triggers demo key fallback |
| 13 | +- **Cookie forwarding**: All cookies from the request are forwarded to Rails |
| 14 | + |
| 15 | +```typescript |
| 16 | +// From app/api/user/route.ts |
| 17 | +const cookieStore = await cookies(); |
| 18 | +const allCookies = cookieStore.getAll(); |
| 19 | +const cookieHeader = allCookies |
| 20 | + .map(({ name, value }) => `${name}=${value}`) |
| 21 | + .join('; '); |
| 22 | +``` |
| 23 | + |
| 24 | +### 2. API Key Injection |
| 25 | +- **Original code**: `import.meta.env.VITE_ABLY_KEY` |
| 26 | +- **After injection**: `"xVLyHw.DQrNxQ:..."` (demo key for logged-out users) |
| 27 | +- **Endpoint injection**: Adds `endpoint: 'sandbox'` for non-production environments |
| 28 | + |
| 29 | +The `updateAblyConnectionKey` utility was ported successfully from Gatsby: |
| 30 | +- Replaces `import.meta.env.VITE_ABLY_KEY` with actual API key |
| 31 | +- Injects Ably endpoint for non-production environments |
| 32 | +- Supports additional key replacements |
| 33 | + |
| 34 | +### 3. Sandpack Integration |
| 35 | +- **Renders correctly**: Code editor and preview both functional |
| 36 | +- **File tabs**: Working (index.js, index.html) |
| 37 | +- **Preview iframe**: Shows "Ably Pub/Sub Demo" interface |
| 38 | +- **Dependencies**: Installed via Sandpack's bundler |
| 39 | + |
| 40 | +### 4. Hydration Safety |
| 41 | +- **No hydration mismatches**: Verified in browser console (0 errors, 0 warnings) |
| 42 | +- **Hydration marker**: Confirms `data-hydration="complete"` |
| 43 | +- **Strategy**: Client-side data fetching with loading state prevents SSR/client mismatch |
| 44 | + |
| 45 | +```tsx |
| 46 | +// Hydration-safe pattern |
| 47 | +const [userData, setUserData] = useState<UserDetails | null>(null); |
| 48 | +const [isLoading, setIsLoading] = useState(true); |
| 49 | + |
| 50 | +useEffect(() => { |
| 51 | + // Fetch on client only - no SSR data means no mismatch |
| 52 | + fetchUserData(); |
| 53 | +}, []); |
| 54 | + |
| 55 | +if (isLoading) return <LoadingState />; // Same on server and initial client render |
| 56 | +``` |
| 57 | + |
| 58 | +### 5. Logged-in vs Logged-out States |
| 59 | + |
| 60 | +| State | Banner | API Key | Works | |
| 61 | +|-------|--------|---------|-------| |
| 62 | +| Logged out | "Not logged in - using demo API key" | Demo Key (xVLyHw...) | Yes | |
| 63 | +| Logged in | "Logged in as {name} - using your real API key" | User's key | Not testable locally* | |
| 64 | + |
| 65 | +*Manual testing with real Rails session required for logged-in state. |
| 66 | + |
| 67 | +## Screenshots |
| 68 | + |
| 69 | +### Example Page - Logged Out State |
| 70 | + |
| 71 | +- Shows "Not logged in - using demo API key" banner |
| 72 | +- API Key displays "Demo Key (xVLyHw...)" |
| 73 | +- Sandpack renders correctly |
| 74 | +- Hydration marker shows "complete" |
| 75 | + |
| 76 | +### Code Editor - API Key Injection |
| 77 | + |
| 78 | +- Line 5: `endpoint: 'sandbox'` - environment injection |
| 79 | +- Line 6: `key: "xVLyHw.DQrNxQ:..."` - API key injection |
| 80 | + |
| 81 | +## Browser Console Output |
| 82 | + |
| 83 | +``` |
| 84 | +Console errors: [] |
| 85 | +Console warnings: [] |
| 86 | +
|
| 87 | +No hydration warnings found in console |
| 88 | +``` |
| 89 | + |
| 90 | +## Build Output |
| 91 | + |
| 92 | +``` |
| 93 | +Route (app) Size First Load JS |
| 94 | +--- / 3.46 kB 105 kB |
| 95 | +--- /_not-found 996 B 103 kB |
| 96 | +--- /api/user 127 B 102 kB |
| 97 | +--- /example 218 kB 319 kB |
| 98 | +``` |
| 99 | + |
| 100 | +Build completed successfully with no TypeScript or compilation errors. |
| 101 | + |
| 102 | +## Learnings |
| 103 | + |
| 104 | +### What Works Well |
| 105 | +1. **Next.js App Router** handles cookies() async correctly in route handlers |
| 106 | +2. **Sandpack with 'use client'** works without hydration issues when data fetching is client-side |
| 107 | +3. **Demo key fallback** provides seamless experience for logged-out users |
| 108 | +4. **Environment variable injection** (endpoint) works alongside API key injection |
| 109 | + |
| 110 | +### Considerations for Production |
| 111 | +1. **CORS**: Cross-origin requests to Rails may need CORS headers configured |
| 112 | +2. **Cookie sharing**: Subdomain cookies (e.g., `*.ably.com`) should work if properly configured |
| 113 | +3. **ISR/Caching**: Pages with API keys should NOT be statically cached - the example page uses client-side fetching which avoids this issue |
| 114 | +4. **Error handling**: Network failures gracefully fall back to demo key |
| 115 | + |
| 116 | +### Potential Issues Identified |
| 117 | +1. **Rails session cookie httpOnly**: The cookie is readable server-side (route handler), but not in client JavaScript - this is actually correct and secure behavior |
| 118 | +2. **CORS for subdomains**: Would need `credentials: 'include'` and proper Access-Control headers on Rails |
| 119 | +3. **Sandpack bundle size**: 218 kB for the example page - acceptable for docs |
| 120 | + |
| 121 | +## Recommendations |
| 122 | + |
| 123 | +1. **Proceed with migration**: The core pattern works. API key injection in Next.js App Router is validated. |
| 124 | + |
| 125 | +2. **Keep client-side fetching**: The pattern of fetching user data client-side avoids hydration mismatches and caching issues with API keys. |
| 126 | + |
| 127 | +3. **Test with real session**: Before full migration, test with actual Rails session to verify: |
| 128 | + - Cookie domain sharing across subdomains |
| 129 | + - CORS configuration |
| 130 | + - Logged-in user flow |
| 131 | + |
| 132 | +4. **Consider caching strategy**: |
| 133 | + - Static pages: Use ISR for content |
| 134 | + - API key pages: Keep client-side fetching (no caching of user-specific data) |
| 135 | + |
| 136 | +## Time Taken |
| 137 | + |
| 138 | +- **Estimated**: 1-2 days |
| 139 | +- **Actual**: ~4 hours |
| 140 | + |
| 141 | +## Files Created |
| 142 | + |
| 143 | +``` |
| 144 | +poc-nextjs/ |
| 145 | +--- app/ |
| 146 | +--- --- api/user/route.ts # Session proxy route handler |
| 147 | +--- --- example/page.tsx # Sandpack with API key injection |
| 148 | +--- --- layout.tsx # Root layout |
| 149 | +--- --- page.tsx # Homepage |
| 150 | +--- lib/ |
| 151 | +--- --- update-ably-connection-keys.ts # Ported utility |
| 152 | +--- package.json |
| 153 | +--- tsconfig.json |
| 154 | +--- next.config.ts |
| 155 | +--- eslint.config.mjs |
| 156 | +--- .env.local |
| 157 | +--- .gitignore |
| 158 | +--- POC_RESULTS.md # This file |
| 159 | +``` |
0 commit comments