Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions apps/preview/.dev.vars.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
# Copy to .dev.vars for `wrangler dev` / `pnpm preview` (never committed).
#
# Optional. Unset, each visitor saves their own v0 key through the app's
# dialog. Set, every visitor shares this key's v0 workspace and credits —
# set the same key on both apps (README, "Connecting v0").
# V0_API_KEY=
13 changes: 13 additions & 0 deletions apps/preview/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
Copyright 2025 Vercel, Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
100 changes: 100 additions & 0 deletions apps/preview/app/api/api-key/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
// Demo only: remove browser-provided API key support before using this example in production.
import { cookies } from 'next/headers'
import { createV0Client } from 'v0'
import { v0Fetch } from '@/lib/v0-fetch'
import { getCloneOrigin } from '@/lib/origins'
import { ensureTrustedPreviewHost, TrustedHostError } from '@/lib/trusted-host'
import { V0_PROXY_API_KEY_COOKIE } from '@/lib/v0-client'

const API_KEY_MAX_AGE = 60 * 60 * 4

export async function OPTIONS(request: Request) {
const headers = getCorsHeaders(request)
return new Response(null, { status: headers ? 204 : 403, headers })
}

export async function PUT(request: Request) {
const corsHeaders = getCorsHeaders(request)
if (!corsHeaders) return forbiddenResponse()

if (process.env.V0_API_KEY) {
return Response.json(
{
message:
'The preview proxy already uses V0_API_KEY. Set it on the web app too, or remove it from the proxy.',
},
{ status: 409, headers: corsHeaders },
)
}

const body = (await request.json().catch(() => null)) as { apiKey?: unknown } | null
const apiKey = typeof body?.apiKey === 'string' ? body.apiKey.trim() : ''

if (!apiKey) {
return Response.json({ message: 'Enter a v0 API key.' }, { status: 400, headers: corsHeaders })
}

const hostname = new URL(request.url).hostname
const client = createV0Client({ auth: apiKey, fetch: v0Fetch })

try {
await ensureTrustedPreviewHost(client, hostname)
} catch (error) {
return Response.json(
{
message:
error instanceof Error ? error.message : 'The preview proxy could not be configured.',
},
{ status: error instanceof TrustedHostError ? error.status : 502, headers: corsHeaders },
)
}

const cookieStore = await cookies()
cookieStore.set(V0_PROXY_API_KEY_COOKIE, apiKey, getCookieOptions(API_KEY_MAX_AGE))

return Response.json({ configured: true }, { headers: corsHeaders })
}

export async function DELETE(request: Request) {
const corsHeaders = getCorsHeaders(request)
if (!corsHeaders) return forbiddenResponse()

const cookieStore = await cookies()
cookieStore.set(V0_PROXY_API_KEY_COOKIE, '', getCookieOptions(0))

return Response.json({ configured: Boolean(process.env.V0_API_KEY) }, { headers: corsHeaders })
}

function getCorsHeaders(request: Request) {
const origin = request.headers.get('origin')
if (origin !== getCloneOrigin()) return undefined

return {
'Access-Control-Allow-Credentials': 'true',
'Access-Control-Allow-Headers': 'Content-Type',
'Access-Control-Allow-Methods': 'PUT, DELETE, OPTIONS',
'Access-Control-Allow-Origin': origin,
'Cache-Control': 'private, no-store',
Vary: 'Origin',
}
}

function getCookieOptions(maxAge: number) {
const production = process.env.NODE_ENV === 'production'

return {
httpOnly: true,
maxAge,
partitioned: production,
path: '/',
sameSite: production ? ('none' as const) : ('lax' as const),
secure: production,
}
}

function forbiddenResponse() {
return Response.json(
{ message: 'This origin cannot configure the preview proxy.' },
{ status: 403 },
)
}
19 changes: 19 additions & 0 deletions apps/preview/app/api/health/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { getCloneOrigin } from '@/lib/origins'

// The deploy's smoke reads this: it answers from the Worker alone — no v0
// call, no key needed — and names the host app origin the build inlined (the
// only origin that may provision this proxy's key). It says whether a server
// key is set, never what it is.
export const dynamic = 'force-dynamic'

export function GET() {
return Response.json(
{
ok: true,
app: 'preview',
cloneOrigin: getCloneOrigin(),
v0ApiKey: process.env.V0_API_KEY ? 'environment' : 'browser',
},
{ headers: { 'Cache-Control': 'no-store' } },
)
}
23 changes: 23 additions & 0 deletions apps/preview/app/api/v0-preview/[chatId]/[[...path]]/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { proxyPreviewRequest } from '@/lib/preview'
import { authorizeProxyRequest } from '@/lib/authorize'

type RouteContext = {
params: Promise<{ chatId: string; path?: string[] }>
}

async function handler(request: Request, context: RouteContext) {
const denied = authorizeProxyRequest(request)
if (denied) return denied
const { chatId, path = [] } = await context.params
return proxyPreviewRequest(request, chatId, path)
}

export {
handler as DELETE,
handler as GET,
handler as HEAD,
handler as OPTIONS,
handler as PATCH,
handler as POST,
handler as PUT,
}
59 changes: 59 additions & 0 deletions apps/preview/app/api/v0-preview/[chatId]/loading/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import { getCloneOrigin } from '@/lib/origins'

function escapeHtml(value: string) {
return value
.replaceAll('&', '&amp;')
.replaceAll('"', '&quot;')
.replaceAll('<', '&lt;')
.replaceAll('>', '&gt;')
}

export async function GET(request: Request, { params }: { params: Promise<{ chatId: string }> }) {
const { chatId } = await params
const previewPath = `/api/v0-preview/${encodeURIComponent(chatId)}`
const requestedReturnTo = new URL(request.url).searchParams.get('returnTo')
const returnTo =
requestedReturnTo === previewPath ||
requestedReturnTo?.startsWith(`${previewPath}/`) ||
requestedReturnTo?.startsWith(`${previewPath}?`)
? requestedReturnTo
: previewPath
const cloneOrigin = getCloneOrigin()

return new Response(
`<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta http-equiv="refresh" content="2;url=${escapeHtml(returnTo)}" />
<script>
const notifyParent = () => parent.postMessage(
{ type: 'v0-preview-loading' },
${JSON.stringify(cloneOrigin)}
)
notifyParent()
setInterval(notifyParent, 250)
</script>
<style>
html, body { height: 100%; margin: 0; }
body {
align-items: center;
background: #fafafa;
color: #666;
display: flex;
font: 14px system-ui, sans-serif;
justify-content: center;
}
</style>
</head>
<body>Loading preview…</body>
</html>`,
{
headers: {
'Cache-Control': 'no-store',
'Content-Type': 'text/html; charset=utf-8',
},
},
)
}
14 changes: 14 additions & 0 deletions apps/preview/app/layout.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import type { Metadata } from 'next'

export const metadata: Metadata = {
title: 'v0 Preview Proxy',
description: 'Isolated preview proxy for the v0 clone example.',
}

export default function RootLayout({ children }: Readonly<{ children: React.ReactNode }>) {
return (
<html lang="en">
<body style={{ margin: 0 }}>{children}</body>
</html>
)
}
100 changes: 100 additions & 0 deletions apps/preview/app/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
import { getCloneOrigin } from '@/lib/origins'

export const dynamic = 'force-dynamic'

export default function PreviewProxyPage() {
const configuration = getConfiguration()

return (
<main
style={{
alignItems: 'center',
background: '#fafafa',
color: '#111',
display: 'flex',
fontFamily: 'ui-sans-serif, system-ui, sans-serif',
justifyContent: 'center',
minHeight: '100vh',
padding: 24,
}}
>
<section
style={{
background: '#fff',
border: '1px solid #e5e5e5',
borderRadius: 12,
boxShadow: '0 12px 32px rgb(0 0 0 / 6%)',
maxWidth: 520,
padding: 32,
width: '100%',
}}
>
<div style={{ alignItems: 'center', display: 'flex', gap: 10 }}>
<span
aria-hidden
style={{
background: configuration.ready ? '#22c55e' : '#f59e0b',
borderRadius: '50%',
height: 8,
width: 8,
}}
/>
<span style={{ color: '#525252', fontSize: 13, fontWeight: 600 }}>
{configuration.ready ? 'Proxy online' : 'Configuration required'}
</span>
</div>
<h1 style={{ fontSize: 24, letterSpacing: '-0.03em', margin: '20px 0 10px' }}>
v0 Preview Proxy
</h1>
<p style={{ color: '#525252', fontSize: 15, lineHeight: 1.6, margin: 0 }}>
This deployment is the isolated origin used to serve generated previews. Open the v0 clone
app to create and view chats.
</p>
<dl
style={{
background: '#fafafa',
border: '1px solid #ededed',
borderRadius: 8,
fontSize: 13,
margin: '24px 0 0',
padding: 16,
}}
>
<dt style={{ color: '#737373', marginBottom: 6 }}>Allowed clone origin</dt>
<dd style={{ fontFamily: 'ui-monospace, SFMono-Regular, monospace', margin: 0 }}>
{configuration.value}
</dd>
</dl>
{configuration.ready ? (
<a
href={configuration.value}
style={{
background: '#111',
borderRadius: 8,
color: '#fff',
display: 'inline-block',
fontSize: 14,
fontWeight: 600,
marginTop: 20,
padding: '10px 14px',
textDecoration: 'none',
}}
>
Open v0 Clone
</a>
) : null}
</section>
</main>
)
}

function getConfiguration() {
try {
return { ready: true, value: getCloneOrigin() }
} catch (error) {
return {
ready: false,
value: error instanceof Error ? error.message : 'V0_CLONE_ORIGIN is invalid.',
}
}
}
10 changes: 10 additions & 0 deletions apps/preview/cloudflare-env.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
// The Worker's environment as getCloudflareContext().env (and process.env,
// which @opennextjs/cloudflare fills from it) sees it: the static-assets
// binding, and the one optional Worker secret the deploy lane sets
// (tooling/wire/worker-secrets.mjs). The app's own code reads neither through
// Worker types — upstream's client code needs the DOM's, which
// @cloudflare/workers-types would shadow — so ASSETS is typed by its shape.
interface CloudflareEnv {
ASSETS: { fetch: typeof fetch }
V0_API_KEY?: string
}
9 changes: 9 additions & 0 deletions apps/preview/eslint.config.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { defineConfig, globalIgnores } from "eslint/config";
import nextVitals from "eslint-config-next/core-web-vitals";
import nextTs from "eslint-config-next/typescript";

export default defineConfig([
...nextVitals,
...nextTs,
globalIgnores([".next/**", ".open-next/**", ".wrangler/**", "next-env.d.ts", "cloudflare-env.d.ts"]),
]);
14 changes: 14 additions & 0 deletions apps/preview/lib/authorize.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
/**
* This proxy serves a credentialed channel into the preview of every chat in
* the deployer's v0 workspace. The same-origin check below is only a baseline
* against browser cross-origin abuse — it does not stop direct non-browser
* requests, and a chat ID is not a secret. Replace or extend it with your
* application's session auth, keyed to which viewer may see which chat, before
* exposing a deployment to untrusted users.
*/
export function authorizeProxyRequest(request: Request): Response | undefined {
const origin = request.headers.get('origin')
if (origin && origin !== new URL(request.url).origin) {
return Response.json({ message: 'Forbidden' }, { status: 403 })
}
}
Loading
Loading