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
104 changes: 96 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,10 +1,98 @@
# nitro-websockets

[Vercel's Nitro + WebSockets Starter](https://github.com/vercel/examples/tree/main/websockets/nitro) on
**Cloudflare Workers**, deployed by [Orun](https://github.com/sourceplane/orun) to stage
and prod on every merge, and then packaged as an Orun baseline.

This commit is the repository's frame: `intent.yaml` (with the placeholder
workspace `ws_CHANGE_ME`, so CI plans nothing until it is linked), the Orun
CI workflow, the shared TypeScript and ESLint configuration, and the spec
index. The work is tracked as an epic under [`specs/epics`](specs/epics/README.md).
Vercel's [Nitro + WebSockets Starter](https://github.com/vercel/examples/tree/main/websockets/nitro)
— a [Nitro v3](https://nitro.build/) + React app where everyone in the room
sees each other's cursors live, with presence and emoji reactions over one
WebSocket — running as one **Cloudflare Worker** whose room is a **Durable
Object**, built by Nitro's own `cloudflare_durable` preset (in place of the
Vercel Functions WebSockets beta), deployed by
[Orun](https://github.com/sourceplane/orun) to stage and prod on every merge.
Packaging it as an Orun baseline is the next milestone (WS2).

The template's code is the code: the React page, the wire protocol, and the
one `defineWebSocketHandler` at `/api/ws`. What the port adds is the preset in
`vite.config.ts`, the Worker's config with the Durable Object, the monorepo
wrapper, a test package, the deploy contract, an `/api/health` route the
deploy smoke-tests, and one change the room needs to survive the Durable
Object hibernating (below); what it swaps is the platform's name and links in
the page. See
[`specs/epics/nitro-websockets`](specs/epics/nitro-websockets/README.md)
for the design, the milestones and the as-built status.

The example is MIT-licensed (vercel/examples); its licence ships with the app
as `apps/web/LICENSE.md`.

## What is here (the app)

| Surface | Where |
|---|---|
| The page — live cursors, presence bar, reactions — the template's React app | `apps/web/app/` |
| `/api/ws` — the room: one WebSocket handler, pub/sub over one `room` topic | `apps/web/server/api/ws.ts` |
| Each connection's identity, kept with its socket so it survives hibernation | `apps/web/server/utils/presence.ts` |
| The wire protocol the page and the room share | `apps/web/shared/types/realtime.ts` |
| `GET /api/health` — the site's name and the environment it runs as | `apps/web/server/api/health.ts` |
| A missing file is a 404, not the page | `apps/web/server/middleware/missing-file.ts` |
| The site's name (the rename's seam) | `apps/web/shared/site.ts` |
| Nitro's config — the template's, plus the `cloudflare_durable` preset | `apps/web/vite.config.ts` |
| Worker config (name, compatibility, the Durable Object and its migration, the build output as the Worker and its Static Assets, per-environment vars) | `apps/web/wrangler.jsonc` |
| Deploy contract | `apps/web/component.yaml` (`cloudflare-worker-turbo`) |
| Tests | `tests/web` (vitest: the room driven through crossws's own Cloudflare adapter over a stand-in Durable Object, hibernation included; the name seam; the page's text) |
| The example's licence (MIT) | `apps/web/LICENSE.md` |

## Getting started

```bash
pnpm install
pnpm typecheck
pnpm lint
pnpm test
pnpm build # vite build → apps/web/.output (the Worker and the page's assets)
```

Run it with Vite's dev server (Node), or the built Worker under workerd with
its Durable Object:

```bash
pnpm --filter @app/web dev # vite dev, http://localhost:3000
pnpm --filter @app/web preview # wrangler dev over the build, http://localhost:8787
curl http://localhost:8787/api/health # {"status":"ok","name":"Nitro WebSockets Starter","environment":"local"}
```

Open the page in two tabs and move the cursor in one.

## How the room runs on Cloudflare

Every WebSocket upgrade to `/api/ws` goes to ONE Durable Object, the room
(Nitro's `cloudflare_durable` preset names it `$DurableObject`, instance
`server`). crossws, Nitro's WebSocket layer, accepts each connection there as
a **hibernatable WebSocket**, so `peer.publish` reaches every socket in the
room, and a quiet room costs nothing while its sockets stay open: the runtime
evicts the object and wakes it for the next message.

A wake keeps the sockets and nothing else: module memory and each peer's
`context` are gone. The template kept its roster in a module `Map` and each
peer's identity in `peer.context`, so after a wake a cursor was dropped
(`if (!identity) return`) and a leave was never announced — measured under
`wrangler dev`, which hibernates an idle room after about a minute. The port
keeps the handler and changes where the state lives: each identity is written
into its socket's serialized attachment beside crossws's own (peer id, URL,
topics), and the roster is read from the room's live sockets. `tests/web`
drives the room through crossws's adapter across a simulated wake.

## How it maps to Vercel

| Vercel | Here |
|---|---|
| Vercel Functions WebSockets beta: the Vercel preset bridges the socket upgrade (`crossws/adapters/vercel`) | Nitro's `cloudflare_durable` preset: the Worker sends every upgrade to one Durable Object, where crossws's Cloudflare adapter accepts it as a hibernatable WebSocket (`vite.config.ts`, `wrangler.jsonc`) |
| The room's state in the function's memory (a roster `Map`, `peer.context`) | Each identity in its socket's attachment, the roster read from the live sockets — they survive the Durable Object hibernating, where module memory does not (`server/utils/presence.ts`) |
| The SPA and its assets on Vercel's CDN | Workers Static Assets over `.output/public`; the Worker answers every other page path with the app, and a missing file with a 404 |
| "Deploy with Vercel" and the Vercel WebSockets docs in the page | A link to Cloudflare's WebSockets-on-Durable-Objects guide; the footer still credits the template (vercel/examples) |
| `vercel dev` · `vercel build` · `vercel deploy` | `vite dev` (or `wrangler dev` over the build) · `vite build` · `wrangler deploy --env <stage\|prod>` |
| Deploy on push | Orun deploys `<repo>-web-{stage,prod}` on merge to `main` and smoke-tests `/api/health` and the WebSocket handshake (`apps/web/component.yaml`) |
| "Deploy with Vercel" (clone the template) | `orun new --blueprint repo-blueprint.yaml` — a new repository, branded, deployed |

## CI

| Workflow | What it runs | Ships to an app |
|---|---|---|
| `ci.yml` | the Orun pipeline, and the only workflow an app carries: `orun plan --changed`, then one job per lane. A pull request runs the verify lanes (the Worker built by Vite and Nitro, type-checked and dry-deployed per environment; the tests' `quick-check` lane installs and checks the package, it does not run them), except the bootstrap's own landings (`orun/BASE-*`), where `plan` alone is the check; a merge deploys stage → prod. It plans nothing while `intent.yaml` names the placeholder workspace `ws_CHANGE_ME`, as this repository does. A manual run (Orunbase's Deploy button, or Run workflow on `main`) plans the environment and components it names under the push-to-main trigger, so they deploy as a merge deploys them | yes |
21 changes: 21 additions & 0 deletions apps/web/LICENSE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License (MIT)

Copyright (c) 2023 Vercel, Inc.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
138 changes: 138 additions & 0 deletions apps/web/app/App.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
import { Badge } from '@/components/ui/badge'
import { buttonVariants } from '@/components/ui/button'
import { HeroBackdrop } from '@/components/hero-backdrop'
import { LiveCanvas } from '@/components/live-canvas'
import { PresenceBar } from '@/components/presence-bar'
import {
CloudflareMark,
GitHubLogo,
MousePointer2,
Sparkles,
Users,
} from '@/components/icons'
import { useRealtime } from '@/hooks/use-realtime'
import { cn } from '@/lib/utils'
import { site } from '@/lib/site'

const features = [
{
icon: MousePointer2,
title: 'Live cursors',
description:
'Every pointer move is broadcast over a single WebSocket and rendered for everyone in the room.',
},
{
icon: Users,
title: 'Presence',
description:
'Join and leave events keep an accurate, shared roster of who is currently connected.',
},
{
icon: Sparkles,
title: 'Reactions',
description:
'Ephemeral emoji bursts fan out to everyone in the room over the same WebSocket connection.',
},
]

export function App() {
const rt = useRealtime()

return (
<div className="relative min-h-screen">
<HeroBackdrop />

<header className="relative z-10 mx-auto flex max-w-5xl items-center justify-between gap-4 px-4 py-5">
<div className="flex items-center gap-2 font-medium text-foreground">
<img src="/nitro.svg" alt="Nitro" className="size-6" />
<span className="text-muted-foreground">×</span>
<CloudflareMark className="size-6" />
<span className="hidden text-sm sm:inline">WebSockets</span>
</div>

<a
href={site.docsUrl}
target="_blank"
rel="noreferrer"
className={cn(
buttonVariants({ variant: 'secondary', size: 'sm' }),
'bg-white text-black hover:bg-white/90',
)}
>
<CloudflareMark className="size-5" />
WebSockets on Durable Objects
</a>
</header>

<main className="relative z-10 mx-auto max-w-5xl px-4 pb-20">
<section className="flex flex-col items-center gap-5 py-10 text-center sm:py-14">
<Badge variant="subtle" className="rounded-full px-3 py-1">
Cloudflare Workers · Durable Objects
</Badge>
<h1 className="max-w-2xl text-4xl font-semibold tracking-tight text-foreground sm:text-5xl">
Realtime, served from a Durable Object
</h1>
<p className="max-w-xl text-balance text-muted-foreground">
A minimal Nitro v3 + React starter on Cloudflare Workers.
Move your cursor below — everything you see is live presence,
cursors, and reactions over one connection.
</p>
<PresenceBar rt={rt} />
</section>

<LiveCanvas rt={rt} />

<section className="mt-16 grid gap-6 sm:grid-cols-3">
{features.map((feature) => (
<div
key={feature.title}
className="flex flex-col gap-2 rounded-lg border bg-card p-5"
>
<feature.icon className="size-5 text-primary" />
<h3 className="font-medium text-foreground">{feature.title}</h3>
<p className="text-sm text-muted-foreground">
{feature.description}
</p>
</div>
))}
</section>
</main>

<footer className="relative z-10 border-t">
<div className="mx-auto flex max-w-5xl flex-col items-center justify-between gap-3 px-4 py-6 text-sm text-muted-foreground sm:flex-row">
<p>
Built with{' '}
<a
href="https://nitro.build"
target="_blank"
rel="noreferrer"
className="text-foreground hover:underline"
>
Nitro
</a>{' '}
and{' '}
<a
href={site.docsUrl}
target="_blank"
rel="noreferrer"
className="text-foreground hover:underline"
>
Cloudflare Durable Objects
</a>
.
</p>

<a
href={site.repo}
target="_blank"
rel="noreferrer"
className={cn(buttonVariants({ variant: 'outline', size: 'sm' }))}
>
<GitHubLogo className="size-4" />
vercel/examples
</a>
</div>
</footer>
</div>
)
}
34 changes: 34 additions & 0 deletions apps/web/app/components/cursor.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import type { RemotePeer } from '@/hooks/use-realtime'

/** A single remote participant's cursor and name label. */
export function Cursor({ peer }: { peer: RemotePeer }) {
return (
<div
className="cursor pointer-events-none absolute left-0 top-0 z-20 will-change-transform"
style={{ left: `${peer.x * 100}%`, top: `${peer.y * 100}%` }}
>
<svg
width="20"
height="22"
viewBox="0 0 20 22"
fill="none"
className="drop-shadow-sm"
>
<path
d="M3 2.5L16.5 11.5L10.2 12.6L13.4 18.8L10.6 20.2L7.4 13.9L3 17.5L3 2.5Z"
fill={peer.color}
stroke="white"
strokeWidth="1.2"
strokeLinejoin="round"
/>
</svg>

<span
className="absolute left-4 top-5 whitespace-nowrap rounded-full px-2 py-0.5 text-xs font-medium text-white shadow-sm"
style={{ backgroundColor: peer.color }}
>
{peer.name}
</span>
</div>
)
}
13 changes: 13 additions & 0 deletions apps/web/app/components/hero-backdrop.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
/**
* Subtle animated glow behind the hero. Pure CSS — two slowly drifting radial
* gradients tinted with the brand accent and masked to fade downward. No
* dependencies, and it respects `prefers-reduced-motion` (see `index.css`).
*/
export function HeroBackdrop() {
return (
<div className="hero-backdrop pointer-events-none absolute inset-x-0 top-0 h-[400px] overflow-hidden">
<div className="hero-backdrop__layer hero-backdrop__layer--a" />
<div className="hero-backdrop__layer hero-backdrop__layer--b" />
</div>
)
}
31 changes: 31 additions & 0 deletions apps/web/app/components/icons.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import type { ComponentProps } from 'react'

export { MousePointer2, Sparkles, Users } from 'lucide-react'

/** A cloud: Cloudflare, where the room runs (a plain mark, not Cloudflare's logo). */
export function CloudflareMark(props: ComponentProps<'svg'>) {
return (
<svg
viewBox="0 0 24 24"
fill="currentColor"
xmlns="http://www.w3.org/2000/svg"
{...props}
>
<path d="M17.5 19H7a5 5 0 0 1-.9-9.92A6.5 6.5 0 0 1 18.6 8.6 5.25 5.25 0 0 1 17.5 19Z" />
</svg>
)
}

/** The GitHub mark. */
export function GitHubLogo(props: ComponentProps<'svg'>) {
return (
<svg
viewBox="0 0 24 24"
fill="currentColor"
xmlns="http://www.w3.org/2000/svg"
{...props}
>
<path d="M12 .5C5.37.5 0 5.87 0 12.5c0 5.3 3.44 9.8 8.21 11.39.6.11.82-.26.82-.58 0-.29-.01-1.04-.02-2.05-3.34.73-4.04-1.61-4.04-1.61-.55-1.39-1.34-1.76-1.34-1.76-1.09-.75.08-.73.08-.73 1.21.09 1.84 1.24 1.84 1.24 1.07 1.84 2.81 1.31 3.5 1 .11-.78.42-1.31.76-1.61-2.67-.3-5.47-1.33-5.47-5.93 0-1.31.47-2.38 1.24-3.22-.12-.3-.54-1.52.12-3.18 0 0 1.01-.32 3.3 1.23a11.5 11.5 0 0 1 6 0c2.29-1.55 3.3-1.23 3.3-1.23.66 1.66.24 2.88.12 3.18.77.84 1.23 1.91 1.23 3.22 0 4.61-2.8 5.62-5.48 5.92.43.37.81 1.1.81 2.22 0 1.6-.01 2.9-.01 3.29 0 .32.21.7.82.58A12 12 0 0 0 24 12.5C24 5.87 18.63.5 12 .5Z" />
</svg>
)
}
Loading
Loading