blockcn

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:

EndpointUsed by
POST /api/aiAsk AI. Streams plain text (or SSE) from Gemini, Claude or OpenAI.
ws://<host>/collaborationCollaboration. A Hocuspocus WebSocket.
POST /api/uploadMedia uploads. Off unless ENABLE_UPLOADS=true.
/api/versions/:roomVersion 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 install

Configure

cp .env.example .env

Then edit server/.env:

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
VariableRequiredPurpose
AI_PROVIDERNogemini (default), anthropic or openai.
GEMINI_API_KEYWith geminiA Google AI Studio key. Ask AI returns 500 without its provider's key. Collaboration doesn't need one.
GEMINI_MODELNoDefaults to gemini-3.6-flash.
ANTHROPIC_API_KEYWith anthropicA Claude Console key.
ANTHROPIC_MODELNoDefaults to claude-opus-5-5.
ANTHROPIC_EFFORTNolow, medium (default) or high. Lower is faster and cheaper.
ANTHROPIC_FALLBACKSNoSet to off to stop re-running declined requests on a fallback model (needed with some proxies).
OPENAI_API_KEYWith openaiAn OpenAI API key.
OPENAI_MODELNoDefaults to gpt-5-mini.
AI_MAX_OUTPUT_TOKENSNoOutput cap per response. Defaults to 4096. With Claude it includes thinking.
AI_LONG_FORM_MAX_OUTPUT_TOKENSNoCap for blog-post and outline. Defaults to 16384.
AI_MAX_TEXT_CHARS / AI_MAX_INSTRUCTION_CHARSNoLongest selection and prompt accepted. Default 12000 / 2000; longer returns 413.
AI_MAX_CONTEXT_CHARSNoDocument context is trimmed to this. Defaults to 8000.
AI_MAX_BODYNoLargest JSON body. Defaults to 64kb.
AI_RATE_LIMIT / AI_RATE_LIMIT_WINDOW_MSNoRequests per IP per window. Default 20 per 60000 ms; over the limit returns 429.
CORS_ORIGINSNoComma-separated browser origins allowed to call the server, or *. Unset allows localhost origins only.
TRUST_PROXYNoBehind 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.
PORTNoDefaults to 8001. HTTP and WebSocket share it.
COLLAB_SECRETFor collaborationHS256 key, 32+ characters, for room tokens. See Authentication.
COLLAB_ALLOW_ANONYMOUSNotrue 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_AUDIENCENoAlso require these iss / aud claims.
COLLAB_STORAGENofile (default) or sqlite.
COLLAB_DATA_DIRNoWhere file storage saves rooms. Defaults to data.
COLLAB_SEEDNoStarter content for brand-new rooms: demo (the editor's demo document) or none (default). See Starter content.
COLLAB_SQLITE_PATHNoThe sqlite database. Defaults to data/collab.sqlite.
COLLAB_SHUTDOWN_TIMEOUT_MSNoHow long shutdown waits for document writes. Defaults to 10000.
ENABLE_UPLOADSNotrue turns on POST /api/upload and serves files from /uploads. Off by default.
UPLOAD_DIRNoWhere uploads are written. Defaults to uploads.
UPLOAD_MAX_BYTESNoLargest accepted file. Defaults to 10485760 (10 MB).
UPLOAD_ALLOWED_TYPESNoComma-separated MIME types, narrowed from the built-in list below.
UPLOAD_PUBLIC_URLNoBase URL in responses, e.g. a CDN in front of /uploads. Defaults to the request's host.
UPLOADS_ALLOW_ANONYMOUSNotrue 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_MBNoTotal 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 dev

You 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/ai with { action, text?, instruction?, param?, context? } (full contract). Unknown actions, a missing or malformed param and bad JSON return 400. Errors are JSON { error }. A successful response is text/plain, written in chunks as the model streams, with the header X-Blockcn-Stream: v1; send Accept: text/event-stream (what sseTransport does) to get data: {"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 with event: error and the same JSON, with no [DONE]. reason is max_tokens (hit the output cap), refusal (the model declined) or error. With Gemini, any finish reason other than STOP counts: RECITATION, OTHER and reasons added later are reported as error (stopped early), never as a finished answer. Failures before any text are 502 with { 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 useCollaboration is 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. On SIGINT/SIGTERM it stops accepting connections, closes open ones, and waits for every pending write (up to COLLAB_SHUTDOWN_TIMEOUT_MS) before exiting. Deployment checklist. COLLAB_GC=off keeps 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/:room stores snapshots beside the room. A read token can list and fetch; a write token can save, delete, and POST /: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, remove COLLAB_ALLOW_ANONYMOUS, and issue room tokens from your backend.
  • Put /api/ai and /api/upload behind 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 /uploads from a separate domain or object storage in production.
  • Set CORS_ORIGINS to your own origins, and TRUST_PROXY if you run behind a proxy.

On this page