Backend
Run the example server that streams Ask AI responses and hosts collaborative rooms.
Ask AI and collaboration ship as clients only. This repo includes one Express server that implements both, on a single port:
| Endpoint | Used by |
|---|---|
POST /api/ai | Ask AI. Streams plain text (or SSE) from Gemini, Claude or OpenAI. |
ws://<host>/collaboration | Collaboration. A Hocuspocus WebSocket. |
POST /api/upload | Media uploads. Off unless ENABLE_UPLOADS=true. |
/api/versions/:room | Version history. Read tokens list and preview; write tokens save, delete, and restore. |
Each room is saved as a Yjs file under data/ (or in SQLite), so documents survive a restart.
Optional
You don't need this server for the basic editor, blocks or export. It isn't installed by shadcn add. Clone the repo and run it next to your app, or treat it as a reference for your own backend.
Get the code
git clone https://github.com/Abhishek758666/blockcn.git
cd blockcn/server
pnpm installConfigure
cp .env.example .envThen edit server/.env:
AI_PROVIDER=gemini
GEMINI_API_KEY=your-key-here
GEMINI_MODEL=gemini-3.6-flash
PORT=8001
COLLAB_ALLOW_ANONYMOUS=true
COLLAB_DATA_DIR=data
COLLAB_SEED=demo
ENABLE_UPLOADS=true
UPLOADS_ALLOW_ANONYMOUS=true| Variable | Required | Purpose |
|---|---|---|
AI_PROVIDER | No | gemini (default), anthropic or openai. |
GEMINI_API_KEY | With gemini | A Google AI Studio key. Ask AI returns 500 without its provider's key. Collaboration doesn't need one. |
GEMINI_MODEL | No | Defaults to gemini-3.6-flash. |
ANTHROPIC_API_KEY | With anthropic | A Claude Console key. |
ANTHROPIC_MODEL | No | Defaults to claude-opus-5-5. |
ANTHROPIC_EFFORT | No | low, medium (default) or high. Lower is faster and cheaper. |
ANTHROPIC_FALLBACKS | No | Set to off to stop re-running declined requests on a fallback model (needed with some proxies). |
OPENAI_API_KEY | With openai | An OpenAI API key. |
OPENAI_MODEL | No | Defaults to gpt-5-mini. |
AI_MAX_OUTPUT_TOKENS | No | Output cap per response. Defaults to 4096. With Claude it includes thinking. |
AI_LONG_FORM_MAX_OUTPUT_TOKENS | No | Cap for blog-post and outline. Defaults to 16384. |
AI_MAX_TEXT_CHARS / AI_MAX_INSTRUCTION_CHARS | No | Longest selection and prompt accepted. Default 12000 / 2000; longer returns 413. |
AI_MAX_CONTEXT_CHARS | No | Document context is trimmed to this. Defaults to 8000. |
AI_MAX_BODY | No | Largest JSON body. Defaults to 64kb. |
AI_RATE_LIMIT / AI_RATE_LIMIT_WINDOW_MS | No | Requests per IP per window. Default 20 per 60000 ms; over the limit returns 429. |
CORS_ORIGINS | No | Comma-separated browser origins allowed to call the server, or *. Unset allows localhost origins only. |
TRUST_PROXY | No | Behind a reverse proxy, so rate limits see client IPs. true or false, a number of proxy hops (e.g. 1), or a comma-separated list of proxy IPs and subnets (10.0.0.0/8, loopback; linklocal and uniquelocal also work). An invalid value stops the server at startup with a message naming it. Prefer a hop count or a list over true, which trusts any X-Forwarded-For. |
PORT | No | Defaults to 8001. HTTP and WebSocket share it. |
COLLAB_SECRET | For collaboration | HS256 key, 32+ characters, for room tokens. See Authentication. |
COLLAB_ALLOW_ANONYMOUS | No | true accepts connections without a token, with write access. For local development only. Without it or a secret, every connection is rejected. |
COLLAB_JWT_ISSUER / COLLAB_JWT_AUDIENCE | No | Also require these iss / aud claims. |
COLLAB_STORAGE | No | file (default) or sqlite. |
COLLAB_DATA_DIR | No | Where file storage saves rooms. Defaults to data. |
COLLAB_SEED | No | Starter content for brand-new rooms: demo (the editor's demo document) or none (default). See Starter content. |
COLLAB_SQLITE_PATH | No | The sqlite database. Defaults to data/collab.sqlite. |
COLLAB_SHUTDOWN_TIMEOUT_MS | No | How long shutdown waits for document writes. Defaults to 10000. |
ENABLE_UPLOADS | No | true turns on POST /api/upload and serves files from /uploads. Off by default. |
UPLOAD_DIR | No | Where uploads are written. Defaults to uploads. |
UPLOAD_MAX_BYTES | No | Largest accepted file. Defaults to 10485760 (10 MB). |
UPLOAD_ALLOWED_TYPES | No | Comma-separated MIME types, narrowed from the built-in list below. |
UPLOAD_PUBLIC_URL | No | Base URL in responses, e.g. a CDN in front of /uploads. Defaults to the request's host. |
UPLOADS_ALLOW_ANONYMOUS | No | true accepts uploads without a token when the request's Origin is in CORS_ORIGINS (or localhost when unset). Local development only. Default false. |
UPLOADS_MAX_TOTAL_MB | No | Total size UPLOAD_DIR may grow to. Defaults to 1024. Uploads past it return 507. |
Never commit .env. The key must stay on the server.
Start it
pnpm devYou should see:
Ask AI on POST /api/ai (gemini, gemini-3.6-flash) on http://localhost:8001
Collaboration (Hocuspocus) on /collaboration: anonymous (dev), files in /…/server/data (ws://localhost:8001)
Uploads on POST /api/upload (token or allowlisted Origin (dev); max 10 MB each, 1 GB total, saved to /…/server/uploads)The collaboration line says anonymous (dev) when COLLAB_ALLOW_ANONYMOUS=true and COLLAB_SECRET is unset. The paths are absolute. With ENABLE_UPLOADS left unset, the last line is Uploads off (set ENABLE_UPLOADS=true to enable POST /api/upload).
For production, run pnpm build, then pnpm start.
Point the editor at it
<AskAI endpoint="http://localhost:8001/api/ai" />useCollaboration({ url: "ws://localhost:8001/collaboration", room: "demo" });createMediaExtensions({
uploadFile: createUploadFile({ endpoint: "http://localhost:8001/api/upload" }),
});In this repo's demo app, set VITE_UPLOAD_URL=http://localhost:8001/api/upload in editor/.env.local instead.
Browsers on localhost can call the server directly. For anything else, list your app's origin in CORS_ORIGINS. The server exposes the X-Blockcn-Stream response header to those origins; if you put your own proxy or CORS layer in front, expose it too (Access-Control-Expose-Headers: X-Blockcn-Stream), or cross-origin clients can't tell a cut-off answer from a finished one. In Next.js you can also proxy /api/ai to the server and leave AskAI on its default endpoint. The demo app's Vite dev server already proxies /api to port 8001.
How it behaves
- Ask AI:
POST /api/aiwith{ action, text?, instruction?, param?, context? }(full contract). Unknown actions, a missing or malformedparamand bad JSON return400. Errors are JSON{ error }. A successful response istext/plain, written in chunks as the model streams, with the headerX-Blockcn-Stream: v1; sendAccept: text/event-stream(whatsseTransportdoes) to getdata: {"text": …}events instead. If the provider fails after text has been sent, the response doesn't just end: plain text ends with a trailer,\n\u0000BLOCKCN_ERROR:{"error":"…","reason":"…"}, and SSE withevent: errorand the same JSON, with no[DONE].reasonismax_tokens(hit the output cap),refusal(the model declined) orerror. With Gemini, any finish reason other thanSTOPcounts:RECITATION,OTHERand reasons added later are reported aserror(stopped early), never as a finished answer. Failures before any text are502with{ error, reason }. The editor's transports read both and show the response as cut off. The selection and document context go in the user message inside tags with a random per-request token, and the system prompt tells the model to treat them as data. Provider errors are logged on the server and returned as a generic message. - Collaboration: the room name passed to
useCollaborationis the document name. The server checks the name, then the token, before it loads anything. It writes the document back a couple of seconds after edits stop. OnSIGINT/SIGTERMit stops accepting connections, closes open ones, and waits for every pending write (up toCOLLAB_SHUTDOWN_TIMEOUT_MS) before exiting. Deployment checklist.COLLAB_GC=offkeeps deleted text in the room file so a version snapshot can be restored after a restart. The file then grows with every edit. - Versions:
/api/versions/:roomstores snapshots beside the room. A read token can list and fetch; a write token can save, delete, andPOST /:id/restore. See Version history.
Uploads
POST /api/upload takes one file in a multipart field named file.
Every upload needs Authorization: Bearer <token>: a token with "permission": "upload", or a room token with "permission": "write", signed with COLLAB_SECRET (see Authentication). A missing or invalid token returns 401; a read token returns 403. A multipart POST is a "simple" request that CORS doesn't block, so without this any website could upload through a signed-in user's browser. For local development, UPLOADS_ALLOW_ANONYMOUS=true accepts token-less requests whose Origin is allowlisted, and rejects the rest with 403. Mint a dev token with pnpm collab:token --upload, and pass it from the editor with getHeaders:
createUploadFile({
endpoint: "http://localhost:8001/api/upload",
// Called before every upload, so a short-lived token from your backend stays fresh.
getHeaders: async () => ({ Authorization: `Bearer ${await fetchUploadToken()}` }),
});It responds 201 with { url, name, size, mimeType }. A file over UPLOAD_MAX_BYTES returns 413. A type that isn't allowed returns 415. When UPLOAD_DIR would grow past UPLOADS_MAX_TOTAL_MB it returns 507. Errors come back as { error }, which the editor shows on the block. Files are saved under a random name with an extension picked from the MIME type, and served from /uploads with nosniff and a sandboxing CSP. PDFs are the exception: Chrome won't render a sandboxed PDF, so they're served Content-Disposition: inline with nosniff and a CSP without sandbox. Allowed by default: PNG, JPEG, GIF, WebP, AVIF, MP4, WebM, QuickTime, MP3, WAV, Ogg, M4A, WebM audio, PDF, plain text and ZIP. SVG and HTML are excluded because they can run script.
Security
Before you deploy
Rate limits and CORS slow down abuse, but they aren't authentication. CORS only binds browsers; any script can call the server. Anyone who can reach it can use your AI key. Before you deploy it:
- Set
COLLAB_SECRET, removeCOLLAB_ALLOW_ANONYMOUS, and issue room tokens from your backend. - Put
/api/aiand/api/uploadbehind your app's auth and add rate limiting. - The MIME type of an upload is what the browser reports. Check file contents if you accept files from untrusted users, and serve
/uploadsfrom a separate domain or object storage in production. - Set
CORS_ORIGINSto your own origins, andTRUST_PROXYif you run behind a proxy.