EN VI

Angular 17 WebSocket is not defined?

2024-03-09 23:00:12
Angular 17 WebSocket is not defined

I have a SpringBoot application, where I configured a WebSocket, which I can connect to with Postman. I have it up on ws://localhost:8050. With only one namespace,"socket".

I tried configuring a native angular websocket and a simple connect, running into an internal server error.

[postman_answer]

I tried to create the WebSocket connection like this.

    this.socket = new WebSocket("ws://localhost:8050/socket")

I am not importing any library like 'ws' for this constructor, it is simply the native one.

I get this error.

[vite] Internal server error: WebSocket is not defined

I expect to be able to connect to the server.

Solution:

When you are working with SSR. You need to prevent server-side rendering or build tools from executing WebSocket code.

I would suggest to check if the window object is available before initializing the WebSocket.

if (typeof window !== 'undefined') {
    this.socket = new WebSocket("ws://localhost:8050/socket");
}

This will ensure the WebSocket is only created in a browser environment.

Or you could work with platformId and isPlatformBrowser. This is a better example for Angular as opposed to the first one, which is more JS.

import { Component, OnInit, Inject, PLATFORM_ID } from '@angular/core';
import { isPlatformBrowser } from '@angular/common';

@Component({
  // Your html, scss etc...
})
export class MyComponent implements OnInit {

    private isBrowser: boolean;

    constructor(@Inject(PLATFORM_ID) private platformId: Object) {
        this.isBrowser = isPlatformBrowser(this.platformId);
    }

    ngOnInit() {
        if (this.isBrowser) {
            // Connect to WebSockets here
        } else {
            // Work without websockets or do nothing
        }
    }
}

With this approach your Angular application should correctly differentiate between server and browser environments, and only attempt to use WebSockets when in the browser.

Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login