Invalid (or missing) WebSocket implementation with SSR (server-side rendering) #215
-
Hi, I am using Apollo-Express for my backend, so I implemented the given example from this repo. For the frontend, I also used the given link & created a splitLink for my httpLink & wsLink. My issue is that my frontend is giving me the following error: Here is a snippet of my backend code that is affiliated with graphql-ws:
And here is the frontEnd code:
The WebSocketLink:
Sorry for the inconvenience & thank you for taking your time to read this. |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 15 replies
-
Hey there, the error claims that the Nevertheless, if you're running the client in a browser, you dont even need const wsLink = new WebSocketLink({
url: 'ws://localhost:4000/graphql',
connectionParams: () => {
const accessToken = getAccessToken().valueOf();
if (!accessToken) return {};
return {
Authorization: accessToken ? `Bearer ${accessToken}` : '',
};
},
- webSocketImpl: WebSocket,
}); P.S. The "Client usage with Apollo" recipe does not use the |
Beta Was this translation helpful? Give feedback.
-
Hey, thank you for the quick answer! Yeah I imported it correctly and I also tried it without the |
Beta Was this translation helpful? Give feedback.
-
The issue here is that the client is being instantiated during server-side rendering on the server. Because the browser's WebSocket is not available there, this issue appears. Recommended solution, as suggested by @praful-chandra in #215 (reply in thread), is to skip over WebSocket parts when not in a browser environment. const wsLink = typeof window === 'undefined' ? null : new WebSocketLink({
url: "ws://localhost:4000/graphql",
connectionParams: () => {
const accessToken = getAccessToken().valueOf();
if (!accessToken) return {};
return {
Authorization: accessToken ? `Bearer ${accessToken}` : '',
};
},
});
An alternative, would be to use the isomorphic W3CWebSocket class from import { w3cwebsocket } from 'websocket';
const wsLink = new WebSocketLink({
webSocketImpl: w3cwebsocket,
url: 'ws://localhost:4000/graphql',
connectionParams: () => {
const accessToken = getAccessToken().valueOf();
if (!accessToken) return {};
return {
Authorization: accessToken ? `Bearer ${accessToken}` : '',
};
},
}); |
Beta Was this translation helpful? Give feedback.
The issue here is that the client is being instantiated during server-side rendering on the server. Because the browser's WebSocket is not available there, this issue appears.
Recommended solution, as suggested by @praful-chandra in #215 (reply in thread), is to skip over WebSocket parts when not in a browser environment.
process.browser
can be used for checking the environ…