Syncing Yjs docs through websocket

So in a nextjs project Im working on, the client connects to a websocket server as such

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>useEffect(() => {
async function fetchDocument(tableId: string) {
try {
const ydoc = new Y.Doc();
const provider = new WebsocketProvider("ws://localhost:3010", `table-${tableId}`, ydoc);
provider.on("status", (event: { status: any; }) => {
console.log(`connection status: ${event.status}`); // logs "connected" or "disconnected"
});
provider.on("sync", (isSynced: boolean) => {
console.log("Synced with server:", isSynced);
});
// Listen for remote changes and update the document state
ydoc.on("update", (update, origin) => {
console.log("Document updated:", ydoc.getText("shared-text").toString(), "origin:", origin);
// Update the document state
setDoc(ydoc);
});
// Ensure the shared-text type is initialized
ydoc.getText("shared-text");
setDoc(ydoc);
setProvider(provider);
} catch (err) {
console.error("Error fetching document:", err);
}
}
if (selectedTableId) {
fetchDocument(selectedTableId);
}
return () => {
if (provider) {
provider.destroy();
}
};
}, [connectionId, selectedTableId]);
</code>
<code>useEffect(() => { async function fetchDocument(tableId: string) { try { const ydoc = new Y.Doc(); const provider = new WebsocketProvider("ws://localhost:3010", `table-${tableId}`, ydoc); provider.on("status", (event: { status: any; }) => { console.log(`connection status: ${event.status}`); // logs "connected" or "disconnected" }); provider.on("sync", (isSynced: boolean) => { console.log("Synced with server:", isSynced); }); // Listen for remote changes and update the document state ydoc.on("update", (update, origin) => { console.log("Document updated:", ydoc.getText("shared-text").toString(), "origin:", origin); // Update the document state setDoc(ydoc); }); // Ensure the shared-text type is initialized ydoc.getText("shared-text"); setDoc(ydoc); setProvider(provider); } catch (err) { console.error("Error fetching document:", err); } } if (selectedTableId) { fetchDocument(selectedTableId); } return () => { if (provider) { provider.destroy(); } }; }, [connectionId, selectedTableId]); </code>
useEffect(() => {
    async function fetchDocument(tableId: string) {
      try {
        const ydoc = new Y.Doc();
        const provider = new WebsocketProvider("ws://localhost:3010", `table-${tableId}`, ydoc);

        provider.on("status", (event: { status: any; }) => {
          console.log(`connection status: ${event.status}`); // logs "connected" or "disconnected"
        });

        provider.on("sync", (isSynced: boolean) => {
          console.log("Synced with server:", isSynced);
        });

        // Listen for remote changes and update the document state
        ydoc.on("update", (update, origin) => {
          console.log("Document updated:", ydoc.getText("shared-text").toString(), "origin:", origin);
          // Update the document state
          setDoc(ydoc);
        });

        // Ensure the shared-text type is initialized
        ydoc.getText("shared-text");

        setDoc(ydoc);
        setProvider(provider);
      } catch (err) {
        console.error("Error fetching document:", err);
      }
    }

    if (selectedTableId) {
      fetchDocument(selectedTableId);
    }

    return () => {
      if (provider) {
        provider.destroy();
      }
    };
  }, [connectionId, selectedTableId]);

And on the websocket server side, it connects just fine and everything like so

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>async function startServer() {
try {
console.log('Connected to database');
wss.on('connection', (ws) => {
const docName = 'not_untitled'; // TODO: Replace with table name logic
loadDocument(docName).then((doc) => {
console.log("Document loaded:" + docName + " " + doc.getText('shared-text').toString());
const awareness = new Awareness(doc);
setupWSConnection(ws, doc, { awareness });
doc.on('update', async () => {
await saveDocument(docName, doc);
});
ws.on('close', () => {
awareness.setLocalState(null);
console.log('Client disconnected');
});
}).catch((err) => {
console.error('Failed to load document:', err);
});
});
console.log(`WebSocket server is running on ws://localhost:3010`);
} catch (err) {
console.error('Failed to start server:', err);
}
}
startServer();
</code>
<code>async function startServer() { try { console.log('Connected to database'); wss.on('connection', (ws) => { const docName = 'not_untitled'; // TODO: Replace with table name logic loadDocument(docName).then((doc) => { console.log("Document loaded:" + docName + " " + doc.getText('shared-text').toString()); const awareness = new Awareness(doc); setupWSConnection(ws, doc, { awareness }); doc.on('update', async () => { await saveDocument(docName, doc); }); ws.on('close', () => { awareness.setLocalState(null); console.log('Client disconnected'); }); }).catch((err) => { console.error('Failed to load document:', err); }); }); console.log(`WebSocket server is running on ws://localhost:3010`); } catch (err) { console.error('Failed to start server:', err); } } startServer(); </code>
async function startServer() {
    try {
      console.log('Connected to database');
  
      wss.on('connection', (ws) => {
        const docName = 'not_untitled'; // TODO: Replace with table name logic
  
        loadDocument(docName).then((doc) => {
          console.log("Document loaded:" + docName + " " + doc.getText('shared-text').toString());
          const awareness = new Awareness(doc);
          setupWSConnection(ws, doc, { awareness });
  
          doc.on('update', async () => {
            await saveDocument(docName, doc);
          });
  
          ws.on('close', () => {
            awareness.setLocalState(null);
            console.log('Client disconnected');
          });
  
        }).catch((err) => {
          console.error('Failed to load document:', err);
        });
      });
  
      console.log(`WebSocket server is running on ws://localhost:3010`);
    } catch (err) {
      console.error('Failed to start server:', err);
    }
  }

startServer();

However the doc on the websocket server and the client have different “shared-text” values and I am not quite sure how they are supposed to sync, as Ive tried doing what the documentation said and looking at similar posts here. The websocket server is getting the correct text from the database Im storing it in, but nothing is being sent between the client and server.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật