Struggled with setting up the WebSocket structure in typescript

Issue

Running the code below results in an error:

index.tsx

import WebSocket from 'ws';

export default function Home() {
  const socket = new WebSocket('ws://localhost:1919/ws');
  
  return (
    <div>Home</div>
  );
}

Error Message:

Unhandled Runtime Error
Error: ws does not work in the browser. Browser clients must use the native WebSocket object

Steps to Reproduce

  • Create Project

    yarn create next-app
    

    Choose all default options.

  • Add ws package

    yarn add ws
    yarn add @types/node @types/ws
    

Answer №1

WebSocket from ws is not intended for use with a web browser, so it's not compatible. Instead, you should utilize the native WebSocket provided by the browser and ensure that you are using it on the client side along with useEffect, as shown below:

import { useEffect } from "react";

export default function HomePage() {
  
  useEffect(() =>
  {
    const socket = new WebSocket('ws://localhost:1919/ws');
  }, [])

  return (
      <div>HomePage</div>
  )
}

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

Tips for dynamically updating localeData and LOCALE_ID for i18n websites during the build process in Angular 9

I am currently developing an application that needs to support multiple languages, specifically up to 20 different languages. The default language set for the application is en-US. The translated versions are generated successfully during the build proces ...

Efficient method for authentication verification in Next.js using nextauth

What would be the ideal method to verify authentication and display a login component using next auth. Do you prefer directing the user to a login page or simply rendering a login component instead of the requested component? I am trying to write clean c ...

Implementing dual language codes for a single locale in internationalization (i18n) efforts

I am currently using i18n to display translations in English and Japanese. The default language is set to English with the code en, but I have recently discovered that my website is not utilizing the correct ISO language code for Japanese, which should be ...

What is the method for adjusting the Accept-Language header in axios using next-i18next outside of a component?

I have been working on exporting a custom function called setLanguageHeader in order to modify the Accept-Language header used by axios. In my axios file, I encapsulated the code as follows: requests.ts: import axios, { AxiosRequestConfig } from 'ax ...

Navigating with Next.js router.push() changes the URL but fails to actually display the page

My Next.js app is running on localhost:3000 and it redirects to a login page if there is no user data. However, when it redirects to the login page, it doesn't render and I encounter this error: Error: Objects are not valid as a React child (found: [o ...

Implement Next.js deployment on NGINX server with a 403 forbidden error

I am currently utilizing Next.js for the frontend and Django for the backend. During development, everything is functioning properly. However, when transitioning to production, I am encountering a 403 Forbidden Error related to /_next/static/chunks. It app ...

Exploring Nuxt's Getters with vuex-class for seamless data retrieval

Currently, I am in the process of developing an application using Nuxt and experimenting with vuex for the first time. Despite following numerous tutorials to set it up, I'm encountering difficulties accessing the store and suspect that the issues may ...

tips on retrieving attributes from a javascript array

I am trying to access the title attribute from an array with only one data record. When I use console.log(data), it displays the result as shown in the picture below. However, if I use console.log(data[0].attributes.title), it returns 'undefined' ...

Conflicting TypeScript enum types: numbers and numbers in NestJS/ExpressJS

Incorporating types into my NestJS server has been a priority. After creating a controller (a route for those who prefer Express), I attempted to define the type for params: public async getAllMessages( @Query('startDate', ValidateDate) start ...

The setting of the custom user agent in the Chrome Extension Manifest Version 3 is not functioning correctly

We currently have an extension that consists of only two files: manifest.json and background.js Despite the browser (Chrome version 112) not reporting any errors, we are facing an issue where the user agent is not being set to 'my-custom-user-agent&a ...

Mapping an array using getServerSideProps in NextJS - the ultimate guide!

I'm facing an issue while trying to utilize data fetched from the Twitch API in order to generate a list of streamers. However, when attempting to map the props obtained from getServerSideProps, I end up with a blank page. Interestingly, upon using co ...

Exploring the Wonders of React Memo

I recently started delving into the world of React. One interesting observation I've made is that when interacting with componentized buttons, clicking on one button triggers a re-render of all button components, as well as the parent component. impo ...

Using redux action in the onPaginationChange function instead of setPaginationState in the given example for the TanStack table - is there a way to

Provided this sample Is there a way to utilize by dispatching a redux action rather than using useState - setPaginationState? onPaginationChange: state => dispatch(browseItemModalActions.setPagination(state)) An error is appearing in the console: ...

Exploring the features of NextJS version 13 with the benefits

Starting from the 13th step, SSR is utilized by default and in order to opt for client side rendering you must specify it at the top like so: 'use client' Currently, my setup involves TypeScript and styled-component integration. Take a look at ...

Utilizing the Next.js Image Component in Harmony with MaterialUI

Although I can easily use the <img> tag, I encounter a problem when attempting to utilize the <Image> component. Instead of the image displaying as intended, all that shows is an empty square of the same size. To showcase the image without reso ...

Can we create an alias for the import path in TypeScript?

import A = require('../../distant/PathToA'); import B = require('./different/path/PathToB'); I am utilizing external modules (commonJS) and browserify, with WebStorm as my editor. If this were just regular javascript, there are severa ...

The Next.js 13 internationalization website continues to redirect to the locale page despite my attempts to remove it

While working on my app with NextJs, I attempted to implement localisation, but it ended up causing confusion and issues. The application started lagging on the i18n route and became unresponsive, even after multiple attempts of restarting the development ...

Unusual class title following npm packaging

Currently, I am working on developing a Vue 3 library with TypeScript. We are using Rollup for bundling the library. Everything works as expected within the library itself. However, after packing and installing it in another application, we noticed that th ...

Encountering 'no overload matches this call' while developing a useReducer using React with Typescript

import { useCallback, useReducer } from "react"; const ARTIST_REDUCER_TYPES = { ADD: "ADD", }; const artistArray = [...Object.values(ARTIST_REDUCER_TYPES)] as const; type ActionReturnedTypes = (typeof artistArray)[number]; type Re ...

Tips for creating TypeScript Google Cloud Functions using webpack

I'm currently facing a challenge while coding a Google Cloud Function using TypeScript. The concept involves having handler functions defined for various Cloud Functions in separate files within the source repository, along with some code that is shar ...