You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NextJS中TipTap协作编辑器Express服务器连接失败求助

问题描述

我在NextJS应用中使用tiptap.dev的协作功能,用Hocuspocus内置CLI命令npx @hocuspocus/cli --port 1234 --sqlite启动本地1234端口服务器时,浏览器间内容同步完全正常。但因为前端要部署到Vercel,我照着文档写了Express.js配置的正式服务器,结果前端连不上,排查半天没头绪,估计是对WebSocket的工作原理理解有问题。

前端代码

import Collaboration from "@tiptap/extension-collaboration"

import StarterKit from "@tiptap/starter-kit"
import { EditorContent, useEditor } from "@tiptap/react"
import React from "react"
import { HocuspocusProvider } from "@hocuspocus/provider"
import * as Y from "yjs"

// A new Y document
const ydoc = new Y.Doc()
// Registered with a WebRTC provider
// const provider = new WebrtcProvider('example-document', ydoc)

const provider = new HocuspocusProvider({
    url: "ws://127.0.0.1:1234",
    name: "example-document",
})

const TipTapEditor = () => {

    const editor = useEditor({
        extensions: [
            StarterKit.configure({
                // The Collaboration extension comes with its own history handling
                history: false,
            }),
            // Register the document with Tiptap
            Collaboration.configure({
                document: provider.document,
            }),
        ],
    })

    return (
        <>
            <EditorContent
                className="w-full h-full border border-black"
                editor={editor}
            />
        </>
    )
}

export default TipTapEditor

Express服务器代码

const express = require("express")
const expressWebsockets = require("express-ws")
const cors = require("cors")
const bodyParser = require("body-parser")
const { Server } = require("@hocuspocus/server")

// Configure Hocuspocus
const server = Server.configure({
    // ...
})

// Setup your express instance using the express-ws extension
const { app } = expressWebsockets(express())

app.use(cors())
app.use(bodyParser.json())

// A basic http route
app.get("/", (request, response) => {
    response.send("Hello World!")
})

app.post("/", (req, res) => {
    res.status(200).json({msg: "success"})
})

// Add a websocket route for Hocuspocus
// Note: make sure to include a parameter for the document name.
// You can set any contextual data like in the onConnect hook
// and pass it to the handleConnection method.
app.ws("/collaboration/:document", (websocket, request) => {
    console.log("ws: ", websocket)
    console.log("req: ", request)
    const context = {
        user: {
            id: 1234,
            name: "Jane",
        },
    }

    server.handleConnection(websocket, request, context)
})

// Start the server
app.listen(3005, () => console.log("Listening on port 3005"))

排查与修复步骤

1. 修正前端WebSocket连接地址

前端里的HocuspocusProvider还指向CLI启动的1234端口,但Express服务器跑在3005端口,且路由前缀为/collaboration,需要修改url参数:

const provider = new HocuspocusProvider({
    url: "ws://127.0.0.1:3005/collaboration",
    name: "example-document",
})

Hocuspocus会自动将name拼接到URL后,最终连接地址为ws://127.0.0.1:3005/collaboration/example-document,刚好匹配Express的路由规则。

2. 完善Hocuspocus Server配置

当前Server配置为空,至少要添加持久化扩展(和CLI一致用SQLite),避免重启服务器丢失数据:

const { Server } = require("@hocuspocus/server")
const { SQLite } = require("@hocuspocus/extension-sqlite")

const server = Server.configure({
  extensions: [
    new SQLite({
      database: "./hocuspocus.db", // 数据库文件路径
    }),
  ],
})

执行npm install @hocuspocus/extension-sqlite安装依赖。

3. 调整CORS配置

虽然已添加cors(),但为避免WebSocket连接被拦截,可明确指定允许的源:

app.use(cors({
  origin: "http://localhost:3000", // NextJS开发环境地址
  credentials: true,
}))

部署到Vercel后,将origin替换为你的Vercel域名,比如https://your-vercel-app.vercel.app。

4. 验证连接状态

启动Express服务器后,打开浏览器控制台查看WebSocket连接状态:

  • 若出现404错误:检查URL是否匹配路由规则
  • 若出现CORS错误:调整CORS配置
  • 若连接成功:查看服务器控制台是否打印连接日志

5. 生产环境配置要点

部署Express服务器到生产环境时:

  • 使用wss://协议(WebSocket over HTTPS),禁止使用ws://
  • 若使用反向代理(如Nginx),需添加WebSocket支持配置:
location /collaboration {
  proxy_pass http://your-server-ip:3005;
  proxy_http_version 1.1;
  proxy_set_header Upgrade $http_upgrade;
  proxy_set_header Connection "upgrade";
  proxy_set_header Host $host;
}

内容的提问来源于stack exchange,提问作者Jarrod

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 19:09:58