I'm trying to use websocket(SocketCluster) with next.js.
My component looks like this
export default class Counter extends React.Component {
static async getInitialProps() {
var socket = socketCluster.connect();
...
return {socket: socket}
}
}
This works when rendered on the client, but does not work when rendered on the server.
Is the a solution or is there a way to disable server rendering?
It's not a good idea to open a connection on the server. Try to fetch the same data via a HTTP endpoint on the server.
In the getInitialProps you'll get an object as the first argument. It has HTTP req and res objects. Based on that, you could identify it's server or client.
static async getInitialProps({ req }) {
const isServer = Boolean(req)
...
}
@arunoda thanks for your reply.
My use case requires websocket therefore using HTTP endpoint is not an option.
It sounds like getInitialProps() is not the right place to establish a socket connection.
Can you recommend a different way?
@mingfang use componentDidMount to open the WebSocket connection componentWillUnmount to close it. That way it's going to only be open in the client.
@sergiodxa is correct.
In the server, if you open a socket connection (or any subscription) there's no way to close it.
@sergiodxa @arunoda that works!
Thank you both for your help.
Most helpful comment
@mingfang use
componentDidMountto open the WebSocket connectioncomponentWillUnmountto close it. That way it's going to only be open in the client.