Running Next.js in ChatGPT: How to Build ChatGPT Apps

This post details how to embed Next.js applications within ChatGPT using the Model Context Protocol (MCP). It addresses specific technical challenges arising from ChatGPT's nested iframe architecture, including: 1. Asset loading by configuring `assetPrefix` in `next.config.ts`. 2. Relative URL resolution by using the HTML `<base>` element. 3. Browser history manipulation by patching `history.pushState` and `history.replaceState` to store only relative paths. 4. Fetch request rewriting for client-side navigation by patching `window.fetch` to target the correct origin. 5. CORS handling for cross-origin requests by implementing middleware to manage `OPTIONS` preflight requests and add `Access-Control-Allow-Origin` headers. 6. Parent frame modifications by ensuring React hydration mismatches are avoided. The post provides code examples for each solution and offers a starter template for building ChatGPT apps with Next.js.