title: Using WebSockets with Next.js
body: <p>I'm wondering what's the best approach to connect into my WebSockets server using Next.js' pages? I'd like that the user could navigate through the pages with one connection, and when he closes the page he also closes the WebSockets connection. I tried using React's Context API:</p>
  <pre><code>const WSContext = createContext(null);
  
  const Wrapper = ({ children }) =&gt; {
    const instance = WebSocket(&quot;ws://localhost:3000/ws&quot;);
  
    return &lt;WSContext.Provider value={instance}&gt;{children}&lt;/WSContext.Provider&gt;;
  };
  
  export const useWS = () =&gt; useContext(WSContext);
  
  export default Wrapper;
  </code></pre>
  <p>It works great, but it does not when it comes to creating a connection. The basic <code>new WebSocket</code> syntax is not working, so I must use a third-party library, like <code>react-use-websocket</code> which I dislike. What's also disturbing is that I cannot close the connection. The Context simply does not know when the page is closed, and also the library does not provide a hook for closing connections.</p>
  <p>I would like to know what's the best approach when it comes to handling WebSockets connection in Next.js.</p>