I’ve been building full‑stack products for a decade, and the last few years I’ve been stitching LLMs into everything from CI pipelines to UI assistants. The most common request I get from product teams is: “Give our users a collaborative document editor that can also suggest formulas, rewrite paragraphs, and auto‑generate charts—without us having to reinvent the wheel.”

Enter the Univer Office SDK. It’s an open‑source, web‑native office stack (spreadsheet, text, slide) that can be dropped into a React or Next.js codebase. In this post I’ll walk through a production‑grade integration: from the npm install to real‑time collaboration, AI‑powered suggestions, persistence, and deployment. I’ll also be blunt about the trade‑offs—cost, latency, and the inevitable edge‑case bugs that surface when you try to run a heavyweight canvas library inside a serverless environment.


Why embed an office suite at all?

Most SaaS products already have a data layer (PostgreSQL, DynamoDB, etc.) and a UI framework (React, Next.js). Adding a full‑featured office experience on top of that stack gives you:

  • Immediate user value – Users can edit spreadsheets, write rich‑text reports, or build slide decks without leaving the app.
  • Collaboration as a first‑class feature – Univer ships with Yjs‑based CRDTs, so you get conflict‑free editing out of the box.
  • AI hooks – Because the document model is exposed as a JavaScript object graph, you can feed it into any LLM for suggestions, formula generation, or data visualisation.

You could try to cobble together a TinyMCE + SheetJS + custom charting solution, but you’ll end up reinventing the same sync layer, undo/redo stack, and clipboard handling that Univer already solves. The SDK is deliberately modular: you can import just the text editor, just the spreadsheet, or the whole suite.

Verification note
The claim that Univer’s core uses Yjs for CRDT‑based collaboration is based on the SDK’s GitHub README and source code. I have not benchmarked its performance against proprietary alternatives.


Getting the Univer Office SDK into a Next.js project

Install the package

# From the root of your Next.js app
npm i @univerjs/core @univerjs/react @univerjs/sheets @univerjs/docs @univerjs/engine-render
# Optional: Yjs integration if you want to use the built‑in provider
npm i @univerjs/yjs

The @univerjs/react package ships a <Univer> component that handles the heavy lifting of mounting the canvas, initializing the core, and cleaning up on unmount. It’s deliberately client‑only, which means we have to guard it against server‑side rendering (SSR) in Next.js.

Configure the loader for SSR

Next.js will try to import every module on the server unless you explicitly opt out. The simplest pattern is to create a thin wrapper that only renders on the client:

// components/UniverWrapper.tsx
import dynamic from 'next/dynamic';
import { useEffect, useState } from 'react';

const UniverClient = dynamic(() => import('./UniverClient'), {
  ssr: false, // <-- crucial
});

export default function UniverWrapper() {
  const [mounted, setMounted] = useState(false);
  useEffect(() => setMounted(true), []);
  return mounted ? <UniverClient /> : null;
}

UniverClient contains the actual <Univer> component and any SDK configuration. By deferring the import until after the first render we avoid the “window is not defined” errors that the canvas‑based renderer would otherwise throw.


Setting up the basic editor component

Minimal React wrapper

// components/UniverClient.tsx
import { Univer, UniverInstanceType } from '@univerjs/core';
import { UniverSheetsPlugin } from '@univerjs/sheets';
import { UniverDocsPlugin } from '@univerjs/docs';
import { UniverRenderEnginePlugin } from '@univerjs/engine-render';
import { useEffect, useRef } from 'react';
import { UniverReact } from '@univerjs/react';

export default function UniverClient() {
  const containerRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (!containerRef.current) return;

    const univer = new Univer();
    univer.registerPlugin(UniverRenderEnginePlugin);
    univer.registerPlugin(UniverSheetsPlugin);
    univer.registerPlugin(UniverDocsPlugin);

    // Create a blank workbook and a blank doc for demo purposes
    const workbook = univer.createUnit(UniverInstanceType.UNIVER_SHEET);
    const doc = univer.createUnit(UniverInstanceType.UNIVER_DOC);

    // Mount the UI
    const root = univer.createRoot(containerRef.current);
    root.mount();

    return () => {
      root.unmount();
      univer.dispose();
    };
  }, []);

  return <div ref={containerRef} style={{ width: '100%', height: '80vh' }} />;
}

A few things to note:

  • UniverInstanceType enumerates the kinds of units you can create (sheet, doc, slide). You can start with just one and add others later.
  • createRoot is the entry point for the React‑based UI that Univer ships. It will render the toolbar, sidebars, and the canvas inside the container you pass.
  • Disposal is important in a hot‑module‑replacement (HMR) dev environment; otherwise you’ll leak WebGL contexts.

Styling and container

Univer’s UI respects the CSS variables it inherits from the host page. I usually add a small reset to keep the toolbar from inheriting my global dark theme:

/* styles/univer.css */
.univer-root {
  --univer-primary-color: #0066ff;
  --univer-bg-color: #fff;
  font-family: system-ui, sans-serif;
}

Import this file in pages/_app.tsx so it’s available everywhere:

import '../styles/univer.css';
import type { AppProps } from 'next/app';

export default function MyApp({ Component, pageProps }: AppProps) {
  return <Component {...pageProps} />;
}

Enabling real‑time collaboration

Univer ships a Yjs provider that syncs the document model over a WebSocket. You can either use the bundled provider (@univerjs/yjs) or roll your own if you need custom auth. I’ll show the bundled approach because it’s the fastest way to get a collaborative demo running.

Choosing a sync provider (Yjs + WebSocket)

Yjs works by exchanging binary updates over a WebSocket. The provider expects a server that simply forwards those updates to all connected peers. The official y-websocket server is a single‑file Node script that can be run as a separate process, but you can also embed it in a Next.js API route.

Server‑side WebSocket endpoint in Next.js

Create a file at pages/api/collab.ts:

// pages/api/collab.ts
import { Server } from 'ws';
import type { NextApiRequest, NextApiResponse } from 'next';
import { setupWSConnection } from 'y-websocket/bin/utils';

let wss: Server | null = null;

export default function handler(req: NextApiRequest, res: NextApiResponse) {
  if (!res.socket.server?.listening) {
    // Initialise the WebSocket server on first request
    wss = new Server({ noServer: true });
    res.socket.server?.on('upgrade', (request, socket, head) => {
      wss?.handleUpgrade(request, socket as any, head, (ws) => {
        setupWSConnection(ws, request);
      });
    });
  }
  res.status(200).end();
}

Verification note
The setupWSConnection helper is exported from y-websocket version 1.5.0 onward. I have not tested this exact snippet on Vercel Edge Functions, which do not support raw WebSockets.

Deploying to Vercel’s serverless functions will not work because they don’t keep a persistent WebSocket listener. For production you’ll want to run this API route on a Node.js server (e.g., a separate Docker container behind a load balancer) or switch to a managed Yjs service like yjs.dev.

Client‑side connection

Back in UniverClient.tsx, register the provider after you create the workbook:

import { UniverYjsPlugin } from '@univerjs/yjs';
import { WebsocketProvider } from 'y-websocket';

...

const workbook = univer.createUnit(UniverInstanceType.UNIVER_SHEET);
const ydoc = univer.getYDoc(workbook.id); // underlying Y.Doc

const provider = new WebsocketProvider(
  `${window.location.origin}/api/collab`,
  workbook.id,
  ydoc
);
provider.on('status', (event) => {
  console.log(`Yjs connection status: ${event.status}`);
});

Now any change you make in the sheet UI will be broadcast to every other client that opened the same workbook.id. The provider automatically handles undo/redo stacks, so you don’t need to write conflict‑resolution code.


Plugging AI into the workflow

The real “AI‑powered” part comes from feeding the document model into an LLM and surfacing the response in the UI. The pattern I use across projects is:

  1. Extract a minimal JSON representation of the current selection (e.g., the active cell range, the paragraph text, or the slide notes).
  2. POST that payload to a server‑side API that calls OpenAI’s Chat Completion endpoint (or any self‑hosted LLM).
  3. Return suggestions (formula, rewrite, chart spec) to the client.
  4. Apply the suggestion via the Univer API.

Prompt design for document assistance

Prompt engineering is the most fragile piece. Here’s a prompt that works well for spreadsheet formula generation:

You are an expert Excel user. Given the following table excerpt and a natural‑language request, output ONLY the Excel formula that satisfies the request.

Table (CSV):
{csv}
Request: {userPrompt}
Answer:

Replace {csv} with a CSV string of the selected range, and {userPrompt} with the user’s typed request (“Calculate the month‑over‑month growth for column B”).

Using OpenAI’s Chat Completion API from the server

Create a new API route at pages/api/ai-suggest.ts:

// pages/api/ai-suggest.ts
import type { NextApiRequest, NextApiResponse } from 'next';
import OpenAI from 'openai';

const openai = new OpenAI({
  apiKey: process.env.OPENAI_API_KEY,
});

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
  if (req.method !== 'POST') {
    res.setHeader('Allow', 'POST');
    return res.status(405).end('Method Not Allowed');
  }

  const { csv, userPrompt } = req.body as { csv: string; userPrompt: string };
  if (!csv || !userPrompt) {
    return res.status(400).json({ error: 'Missing csv or userPrompt' });
  }

  const prompt = `
You are an expert Excel user. Given the following table excerpt and a natural-language request, output ONLY the Excel formula that satisfies the request.

Table (CSV):
${csv}
Request: ${userPrompt}
Answer:
`;

  try {
    const completion = await openai.chat.completions.create({
      model: 'gpt-4o-mini',
      messages: [{ role: 'user', content: prompt }],
      temperature: 0,
    });
    const answer = completion.choices[0].message.content?.trim() ?? '';
    res.status(200).json({ suggestion: answer });
  } catch (err) {
    console.error('OpenAI error', err);
    res.status(500).json({ error: 'AI service failed' });
  }
}

Verification note
The openai npm package version 4.x uses the chat.completions.create method as shown. I have not verified the exact response shape for gpt-4o-mini; adjust the model name if you encounter an “model not found” error.

Exposing an endpoint for the editor

In the UI you can add a small “Ask AI” button to the toolbar. When clicked, it gathers the current selection, builds the CSV, and calls the endpoint:

// components/AiAssistButton.tsx
import { useCallback } from 'react';
import { useUniverInstance } from '@univerjs/react';
import { UniverInstanceType } from '@univerjs/core';

export default function AiAssistButton() {
  const { getInstance } = useUniverInstance();

  const handleClick = useCallback(async () => {
    const sheet = getInstance(UniverInstanceType.UNIVER_SHEET);
    if (!sheet) return;

    const selection = sheet.getSelectionModel().getCurrentSelection();
    const range = selection?.range;
    if (!range) return;

    const csv = sheet.getRangeValues(range).map(row => row.join(',')).join('\n');
    const userPrompt = prompt('What do you want to do with this data?');

    const resp = await fetch('/api/ai-suggest', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ csv, userPrompt }),
    });
    const { suggestion } = await resp.json();

    if (suggestion) {
      // Insert the formula into the active cell
      const activeCell = sheet.getActiveCell();
      sheet.setCellValue(activeCell, suggestion);
    }
  }, [getInstance]);

  return (
    <button onClick={handleClick} className="univer-toolbar-button">
      🤖 Ask AI
    </button>
  );
}

You can drop this button into the toolbar by extending the UniverToolbarPlugin (see the SDK docs for registerToolbarItem). The same pattern works for Docs (text rewrite) or Slides (auto‑generate speaker notes).


Persisting documents

Real‑world apps need to store the document state between sessions. The Univer core can export its internal model as a binary .univer blob, which you can persist in any object store. I like Supabase because it gives you Postgres for metadata and S3‑compatible storage for the blobs, all behind a single SDK.

Example schema

-- supabase/public.sql
create table documents (
  id uuid primary key default gen_random_uuid(),
  owner_id uuid references auth.users(id),
  title text not null,
  created_at timestamp default now(),
  updated_at timestamp default now()
);

create table document_blobs (
  doc_id uuid primary key references documents(id) on delete cascade,
  blob bytea not null,
  version int not null default 1
);

API route to save/load

// pages/api/doc/[id].ts
import type { NextApiRequest, NextApiResponse } from 'next';
import { createClient } from '@supabase/supabase-js';
import { Univer } from '@univerjs/core';
import { getServerSession } from 'next-auth/next';
import { authOptions } from '../../auth/[...nextauth]';

const supabase = createClient(
  process.env.NEXT_PUBLIC_SUPABASE_URL!,
  process.env.SUPABASE_SERVICE_ROLE_KEY!
);

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
  const session = await getServerSession(req, res, authOptions);
  if (!session) return res.status(401).json({ error: 'Unauthenticated' });

  const { id } = req.query as { id: string };

  if (req.method === 'GET') {
    const { data, error } = await supabase
      .from('document_blobs')
      .select('blob')
      .eq('doc_id', id)
      .single();

    if (error) return res.status(404).json({ error: 'Not found' });
    const univer = new Univer();
    await univer.load(data!.blob);
    const snapshot = univer.save();
    return res.status(200).json({ snapshot });
  }

  if (req.method === 'POST') {
    const { snapshot } = req.body as { snapshot: Uint8Array };
    const { error } = await supabase
      .from('document_blobs')
      .upsert({ doc_id: id, blob: snapshot })
      .eq('doc_id', id);
    if (error) return res.status(500).json({ error: error.message });
    return res.status(200).json({ success: true });
  }

  res.setHeader('Allow', ['GET', 'POST']);
  res.status(405).end('Method Not Allowed');
}

The client can call /api/doc/[id] on mount to load the saved snapshot, and on a debounce timer (e.g., every 10 seconds) POST the current snapshot back. The SDK’s univer.save() returns a Uint8Array that you can send directly.


Handling authentication and permissions

I usually pair NextAuth.js (v4) with Supabase’s JWT verification. The flow is:

  1. User signs in via Google, GitHub, or email link.
  2. NextAuth stores the session in an HttpOnly cookie.
  3. When the client opens a document, we fetch the document metadata via /api/doc/[id]. The server checks that owner_id === session.user.id (or that the user belongs to a shared‑access list).
  4. The WebSocket provider receives the user ID via a query param (?docId=…&userId=…) and can enforce read‑only vs. edit permissions on the Yjs level.
// pages/_app.tsx (excerpt)
import { SessionProvider } from 'next-auth/react';
import type { AppProps } from 'next/app';

export default function MyApp({ Component, pageProps }: AppProps) {
  return (
    <SessionProvider session={pageProps.session}>
      <Component {...pageProps} />
    </SessionProvider>
  );
}

In the Yjs provider:

const provider = new WebsocketProvider(
  `${window.location.origin}/api/collab?docId=${docId}&userId=${session?.user?.id}`,
  docId,
  ydoc
);

On the server side you can read userId from the query string and reject connections that don’t match the session cookie. This is a lightweight guard; for stricter security you’d want to embed the permission check inside the Yjs server itself (e.g., by extending setupWSConnection).

Verification note
The setupWSConnection function does not natively parse query parameters for auth. The snippet above assumes you add custom middleware to the WebSocket upgrade handler.


Deploying to Vercel (or self‑hosted)

Edge functions considerations

Vercel’s Edge Runtime cannot run native Node modules (like ws), so the WebSocket sync server must be deployed elsewhere (e.g., Railway, Fly.io, or a Kubernetes pod). The rest of the Next.js app—pages, API routes for AI and persistence—works fine on Edge or Serverless.

If you decide to keep everything on Vercel, you can replace the Yjs WebSocket with WebRTC (via y-webrtc) which runs entirely in the browser. The trade‑off is higher latency for users behind strict NATs, but you avoid a dedicated server.

Environment variables

Variable Example Where it lives
NEXT_PUBLIC_SUPABASE_URL https://xyzcompany.supabase.co Vercel → Project Settings → Environment Variables (Preview & Production)
SUPABASE_SERVICE_ROLE_KEY service_role secret Vercel → Environment Variables (only Production)
OPENAI_API_KEY sk-… Vercel → Environment Variables (Secret)
NEXTAUTH_SECRET a-long-random-string Vercel → Environment Variables
NEXTAUTH_URL https://myapp.vercel.app Vercel → Environment Variables

Never expose the service‑role key to the client; keep it server‑only.


Debugging common pitfalls

SSR errors with canvas

Univer’s rendering engine uses WebGL. If you accidentally import a component that touches document during SSR, you’ll see:

ReferenceError: window is not defined

The fix is always the same: wrap the import in dynamic(..., { ssr: false }) or guard with if (typeof window !== 'undefined').

CORS with the AI endpoint

When you call /api/ai-suggest from the client, the browser will send a preflight OPTIONS request if you include custom headers. Make sure your Next.js API route does not block it:

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
  if (req.method === 'OPTIONS') {
    res.setHeader('Access-Control-Allow-Methods', 'POST,OPTIONS');
    res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
    return res.status(200).end();
  }
  // …rest of handler
}

In production you’ll likely have the same domain for both front‑end and API, so CORS isn’t a problem, but it’s worth remembering when you spin up a separate AI microservice.


Performance tuning

Lazy loading the SDK

The Univer bundle is ~2 MB gzipped. If your app’s primary entry point isn’t the office suite, you should lazy‑load it:

// pages/workspace.tsx
import dynamic from 'next/dynamic';
import { Spinner } from '@/components/Spinner';

const UniverWrapper = dynamic(() => import('@/components/UniverWrapper'), {
  loading: () => <Spinner />,
});

export default function WorkspacePage() {
  return (
    <div className="workspace">
      <UniverWrapper />
    </div>
  );
}

Memoizing the editor instance

Creating a new Univer instance on every re‑render is expensive. Keep the instance in a useRef and only re‑initialize when the document ID changes:

const univerRef = useRef<Univer | null>(null);
useEffect(() => {
  if (univerRef.current) return; // already created
  const univer = new Univer();
  // register plugins …
  univerRef.current = univer;
  // mount …
}, [docId]);

When to walk away

Embedding a heavyweight office suite is not a silver bullet. Consider the following before you commit:

Factor What to watch
Cost Each AI suggestion incurs an LLM token charge. If you expect thousands of daily edits, the bill can balloon quickly. See my post on AI feature cost budgeting for a rough model.
Latency The round‑trip to OpenAI (or a self‑hosted model) adds ~200 ms overhead. For real‑time formula generation this is acceptable, but for auto‑complete while typing you may need a local model.
Compliance If your data is PHI or PCI, sending raw CSV snippets to an external LLM is a red flag. You’ll need an on‑prem LLM or a data‑masking layer.
Complexity The combination of WebSocket sync, canvas rendering, and AI endpoints creates a “three‑layer” failure surface. If your team is small, you might be better off integrating a SaaS editor like Google Docs via an iframe.

If any of those rows turn red for your product, you may want to postpone the office suite until you have a dedicated infra budget.


Wrap‑up

Embedding an AI‑powered office suite in a React/Next.js app is now a tractable engineering problem thanks to the Univer Office SDK. The steps I covered—installing the SDK, shielding it from SSR, wiring up Yjs for collaboration, adding an LLM‑backed suggestion endpoint, persisting snapshots, and securing the whole flow—are all things you can ship in a single sprint if you already have a Next.js codebase and a cloud provider.

The biggest unknowns are operational: running a reliable WebSocket server at scale, budgeting for LLM usage, and meeting compliance requirements. Those are not solved by the SDK; they belong to your architecture and product decisions.

If you’re already experimenting with AI agents in the UI, you might find the patterns from my earlier post on Embedding AI agents in React & Next.js using the AG‑UI Protocol useful for structuring the “Ask AI” button. And if you care about security scanning of the generated formulas or markdown, check out the workflow I described in AI‑Powered Security Scanning for TypeScript.

Happy hacking—may your spreadsheets stay sane and your LLMs stay cheap.

Conclusion

Embedding an office suite is a large surface area for one feature, so adopt it only when the spreadsheet or document is the product rather than a feature inside it. The integration itself is the easy part; the state model, the save semantics and the conflict story are what decide whether it holds up.

The editor is the visible part; persistence and conflicts are the work, and backend and API development covers that side. I do this kind of integration under full-stack development. The SDK is documented at docs.univer.ai. If you are weighing a full office suite against a simple grid, tell me what users actually do in it.

Frequently asked questions

When is embedding an office suite the right call?

When editing a spreadsheet or document is the product, not a side feature. If users only need to view or lightly edit a table, a purpose-built grid is smaller, faster and far less to maintain.

How does Univer compare with building on a grid component?

A grid component gives you a table. Univer gives you formulas, formatting, multiple sheets and file compatibility, which is a lot of work you would otherwise own. The trade is bundle size and a much larger API surface.

Where should document state live?

On the server, with the client holding a working copy. If the browser is the only place the document exists, a refresh loses work, and two tabs will silently overwrite each other.

What is the hardest part of this integration?

Persistence and conflict handling, not rendering. Deciding who wins when two people edit the same cell is a product decision that the SDK cannot make for you.