Next.js Discord

Discord Forum

Noob here: Auto connecting to Websocket inside the layout?

Unanswered
Dwarf Crocodile posted this in #help-forum
Open in Discord
Dwarf CrocodileOP
I want my App to automatically establish the WS connection with a user's browser. Regardless of what page they first ever open.
Should i connect to the WS inside the layout like that (i use zustand btw)
'use client'
import { useEffect } from "react";
import { useSocketStore } from "./store/socket_store";

export function SocketLayer() {
    const initSocket = useSocketStore((state) => state.initSocket);
    useEffect(() => {
        initSocket()
            .then(() => console.log("Socket connected!!"))
            .catch(console.error);

        return () => {
            useSocketStore.getState().disconnect();
        }
    }, [initSocket]);

    return null;
}


and then someting like:
export default function RootLayout({
  children,
}: Readonly<{
  children: React.ReactNode;
}>) {
  return (
    <html lang="en">
      <body
        className={`${geistSans.variable} ${geistMono.variable} antialiased`}
      >
        <SocketLayer />
        {children}
      </body>
    </html >
  );
}


Or is there a better way?

2 Replies