Issue with web socket connections arising when attempting to add subscriptions within the URQL client

Seeking assistance in setting up subscriptions on URQL Client with Apollo server. I am facing difficulty getting the web socket to function properly on the client-side. Any guidance or support would be greatly appreciated. It seems like there may be an issue with the client-side implementation rather than the communication between the server and client.

Here is the code snippet that I added to my client:

import { SubscriptionClient } from "subscriptions-transport-ws";

const subscriptionClient = new SubscriptionClient(
  "ws://localhost:4000/subscriptions",
  {
    reconnect: true,
  }
);

const CreateUrqlClient = (ssrExchange: any, ctx: any) => {
  let cookie = "";
  if (isServer()) {
    cookie = ctx?.req?.headers.cookie;
  }
  return {
    url: process.env.NEXT_PUBLIC_API_URL,
    fetchOptions: {
      credentials: "include" as const,
      headers: cookie
        ? {
            cookie,
          }
        : undefined,
    },
    exchanges: [
      dedupExchange,
      subscriptionExchange({
        forwardSubscription: (operation) =>
          subscriptionClient.request(operation),
      }),
      cacheExchange,
      errorExchange,
      ssrExchange,
      fetchExchange,
    ],
  };
};
export default CreateUrqlClient;

I encountered the following error message (Server Error Error: Unable to find native implementation, or alternative implementation for WebSocket!). Additionally, I attempted using ws (not compatible with browsers) and WebSocket directly (unsure of correct usage), but have not been successful in resolving the issue.

https://i.sstatic.net/L8OcO.png

Answer №1

Experiment with this:

const subscriptionClient =process.browser ? new SubscriptionClient('ws://localhost:4000/subscriptions', { reconnect: true }) as any : null;

This solution worked for me.

Answer №2

To resolve a related issue, I used the following approach:

import NodeWebSocket from 'ws';

const wsClient = createWSClient({
    url: `ws://example.com/socket`,
    webSocketImpl: typeof window === 'undefined' ? NodeWebSocket : WebSocket
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue with React Context: The type 'Dispatch<SetStateAction<GiftsType>>' cannot be assigned to type '(arr1: string[], arr2: string[]) => void'

I'm currently working on a project in React+TS where I need to create a context that takes two string arrays and updates an object's state with these arrays. I keep encountering a title typo error in the setChoices function inside the return stat ...

Arranging Angular Cards alphabetically by First Name and Last Name

I am working with a set of 6 cards that contain basic user information such as first name, last name, and email. On the Users Details Page, I need to implement a dropdown menu with two sorting options: one for sorting by first name and another for sorting ...

typescript global variables are not functioning as expected

Encountering an issue with the signin function implementation in my application. Despite having a global declaration for this function, I am getting an error stating 'Element implicitly has an 'any' type because type 'typeof globalThis& ...

Steps for creating an instance of the same type within a base class in TypeScript

When B extends A, is it possible for A to define a method that generates a new instance of B? class SetA { constructor(public items:any[]) { } createNew(items){ return new *typeof this*(items); //<-- insert actual implementation here ...

Fixing the forwardRef issue with react-router-dom and material-ui

Despite implementing the forwardRef as recommended in various posts and Material-UI website examples, I am still encountering a warning in the console that has me puzzled. I am working on setting up a drawer with a list of items that are React Router link ...

Exploring the power of Node JS with Promise.all and forEach within a nested array

When working on a Node app with typescript, I encountered the need to iterate through an array while calling an asynchronous function inside the loop to fetch information about related items for each item in the array. The function is called for each relat ...

The type CustomModel[] lacks the property 'XYZ' in it

Using TypeScript v2.7.2 Check out the code snippet below: import { Component, OnInit } from '@angular/core'; import { Ingredient } from "../shared/ingredient.model"; @Component({ selector: 'app-shopping-list', templateUrl: ' ...

Executing Promises in TypeScript Sequentially

I have a collection of doc objects and I need to send an API request for each doc id in the list, executing the requests in a sequential manner. In my Typescript code, I am using Promise.all and Promise.allSelected to achieve this. [ { "doc_id&q ...

Angular2: Separate router-outlets within individual modules

I am working on an Angular app that consists of multiple modules (modules A and B are lazy loaded): MainModule, ModuleA, ModuleB Currently, all content is loaded in the AppComponent (which has a router-outlet tag). However, I would like to restructure it ...

ng-select issue: list not refreshing

I am encountering an issue with the method below that updates the modules array. Even though the console displays the result correctly, the ng-select does not update the list accordingly. I attempted to use this.modules=[...elements], but it did not work ...

Issue with Angular custom toggle functionality not functioning properly on mobile devices

I've been working on creating a custom toggle feature in Angular. While everything runs smoothly on desktop, I'm encountering issues on mobile devices. On desktop, the toggle works by clicking and dragging to the right, whereas on mobile, it shou ...

Looking for guidance on where to find a functional code sample or comprehensive tutorial on working with ViewMetadata in Angular2

I am currently trying to understand the relationship between viewmetadata and the fundamental use of encapsulation: ViewEncapsulation, including ViewEncapsulation.Emulated and ViewEncapsulation.None. Here is a link for further information: https://angula ...

Change the country name to all lowercase letters

I'm attempting to retrieve the country flag icon of the Open Weather Map API. For example: The JSON response for the country code from the API request is in uppercase. To obtain the correct icon for the country, I need the country code in lowercase. ...

What could be causing the conditional div to malfunction in Angular?

There are three conditional div elements on a page, each meant to be displayed based on specific conditions. <div *ngIf="isAvailable=='true'"> <form> <div class="form-group"> <label for ...

Using TypeScript to Implement Content Security Policy Nonce

I encountered an issue with my TypeScript Express project while attempting to implement a CSP Nonce using Helmet. app.use(helmet.contentSecurityPolicy({ useDefaults: true, directives: { scriptSrc: ["'self'", (req, res) = ...

Using React-Bootstrap with TypeScript in your project

I'm currently working on creating a navigation bar using react-bootstrap. I've already installed the node-module as follows: "@types/react-bootstrap": "^0.32.11",. However, when I try to use it in my hello.tsx component, I encounter a compile err ...

What is the correct way to integrate nested forms using Validator and Control Value Accessor?

One challenge in my application is the need for a reusable nested form component like Address. I wanted my AddressComponent to manage its own FormGroup without the need for external input. During an Angular conference (video, presentation), Kara Erikson f ...

Prettier seems to be producing varied outcomes across various machines

My teammate and I are collaborating on the same project, but we're facing an issue where our Prettier configurations conflict. Each time we push our code to Github, his Prettier format overrides mine. Here's an example of his formatting: const in ...

How can I retrieve only the pertinent information stored in Firestore?

I'm struggling to filter out only the data relevant to a specific "userId" from Firestore, as currently everything in the database is being printed. I've attempted to make changes based on advice I received but it hasn't resulted in any impr ...

Svelte: The selection issue that's not updating [CSS glitch]

I am utilizing a Svelte Selection component to fetch and display data in a dropdown. Users have the ability to select different properties, which is functioning correctly. However, I am encountering an issue when attempting to preselect certain options des ...