vercel / next.js

The React Framework
https://nextjs.org
MIT License
125.91k stars 26.87k forks source link

Trying to load a browser-only module on non-browser environment #69863

Closed iamaliybi closed 1 month ago

iamaliybi commented 1 month ago

Link to the code that reproduces this issue

https://github.com/there-is-no-link

To Reproduce

Dependencies

  1. Create Lightstream.ts file and put the code below in it:
    
    import routes from '@/api/routes';
    import { getBrokerClientId } from '@/utils/cookie';
    import { LightstreamerClient, type ClientListener } from 'lightstreamer-client-web';
    import Subscribe from './Subscribe';
    import { type SubscriptionOptions } from './lightstream.d';

class Lightstream { / Public / public connection: LightstreamerClient; public adapter: string;

/* Private */
private readonly _address: string;
private readonly _port: string;
private _username: string | 'anonymous' = 'anonymous';

/* Subscriptions */
private readonly _subscriptions: Subscribe[] = [];

/* Handlers */
private _handlers: ClientListener = {};

constructor() {
    this.connection = new LightstreamerClient();
    this.adapter = 'adapter_name';

    /* Private */
    this._address = 'http://127.0.0.1';
    this._port = '443';

    Object.seal(this);
}

start() {
    this._setup();
    this.connection.addListener(this._handlers);

    // connect
    this._connect();
    return this;
}

restart() {
    this._disconnect();

    setTimeout(() => {
        this.connection.connectionDetails.setUser(this._username);
        if (this._username === 'anonymous') this.connection.connectionDetails.setPassword('anonymous');
        else this.setPassword();

        this._connect();
    }, 250);
}

getStatus() {
    return this.connection.getStatus();
}

subscribe(options: SubscriptionOptions) {
    const subscribe = new Subscribe(this.connection, options);
    this._subscriptions.push(subscribe);

    return subscribe;
}

addEventListener<T extends keyof ClientListener>(channel: T, listener: ClientListener[T]) {
    this._handlers[channel] = listener;

    return this;
}

removeEventListener(channel: keyof ClientListener) {
    delete this._handlers[channel];

    return this;
}

disconnect() {
    this.connection.disconnect();
}

setUsername(username: null | string) {
    this._username = username ?? 'anonymous';
    return this;
}

setPassword() {
    const password = getBrokerClientId()[0] ?? 'anonymous';
    this.connection.connectionDetails.setPassword(password);
}

/* Getters */
get serverAddress(): string {
    return this._address + ':' + this._port;
}

/* Private */
private _setup() {
    this.connection.connectionDetails.setServerAddress(this.serverAddress);
    this.connection.connectionDetails.setAdapterSet(this.adapter);
    this.connection.connectionDetails.setUser(this._username);
    if (this._username === 'anonymous') this.connection.connectionDetails.setPassword('anonymous');
    else this.setPassword();
}

private _connect() {
    if (this.connection) this.connection.connect();
}

private _disconnect() {
    if (this.connection) this.connection.disconnect();
}

}

const lightStreamInstance = new Lightstream();

export type { Lightstream };

export default lightStreamInstance;

2. Create `LightstreamRegistry.tsx` file and put the code below in it:
```typescript
'use client';

import lightStreamInstance, { type Lightstream } from '@/classes/Lightstream';
import { useAppDispatch } from '@/features/hooks';
import { setLsStatus } from '@/features/slices/uiSlice';
import { useUserInfo } from '@/hooks';
import { useEffect, useRef } from 'react';

interface LightstreamRegistryProps {
    children: React.ReactNode;
}

const LightstreamRegistry = ({ children }: LightstreamRegistryProps) => {
    const lightstream = useRef<Lightstream | null>(null);

    const dispatch = useAppDispatch();

    const { data: userInfo, isLoading } = useUserInfo();

    const registerLightstream = () => {
        lightstream.current = lightStreamInstance
            .setUsername(userInfo?.nationalCode ?? null)
            .addEventListener('onStatusChange', (status) => {
                dispatch(setLsStatus(status as LightstreamStatus));
            })
            .start();
    };

    const updateLightstream = () => {
        if (!lightstream.current) return;
        lightstream.current.setUsername(userInfo?.nationalCode ?? null).restart();
    };

    useEffect(() => {
        if (isLoading) return;

        if (!lightstream.current) registerLightstream();
        else updateLightstream();
    }, [userInfo, isLoading]);

    return children;
};

export default LightstreamRegistry;
  1. Create Providers.tsx file and put the code below in it:
    
    import dynamic from 'next/dynamic';

const LightstreamRegistry = dynamic(() => import('@/components/common/Registry/LightstreamRegistry'), { ssr: false, });

interface ProvidersProps { children: React.ReactNode; }

const Providers = ({ children }: ProvidersProps) => { return {children}; };

export default Providers;


4. Create `Wrapper.tsx`
```typescript
'use client';

import { useTranslations } from 'next-intl';
import React, { useEffect, useState } from 'react';
import ErrorBoundary from '../common/ErrorBoundary';

interface IWrapper {
    children: React.ReactNode;
}

const Wrapper = ({ children }: IWrapper) => {
    const t = useTranslations('common');

    const [mount, setMounted] = useState(false);

    useEffect(() => {
        setMounted(true);
    }, []);

    if (!mount) return null;

    return (
        <ErrorBoundary>
            <div className='hidden h-screen md:flex'>
                <ErrorBoundary>{children}</ErrorBoundary>
            </div>
        </ErrorBoundary>
    );
};

export default Wrapper;
  1. Create src/app/layout.tsx
    
    import Providers from '@/components/common/Providers';
    import Wrapper from '@/components/layout/Wrapper';
    import { getDirection } from '@/utils/helpers';
    import { NextIntlClientProvider } from 'next-intl';
    import { getLocale, getMessages } from 'next-intl/server';
    import dynamic from 'next/dynamic';
    import Script from 'next/script';
    import metadata from '../metadata';

interface ILayout extends INextProps {}

const Layout = async ({ children }: ILayout) => { const locale = await getLocale(); const messages = await getMessages();

return (
    <html lang={locale} dir={getDirection(locale)}>
        <body>
            <NextIntlClientProvider messages={messages}>
                <Providers>
                    <Wrapper>{children}</Wrapper>
                </Providers>
            </NextIntlClientProvider>
        </body>
    </html>
);

};

export { metadata };

export default Layout;


6. Create `src/app/page.tsx`
```typescript
const Page = () => {
    return <div>Hello World!</div>;
};
  1. Start the application in development (next dev)
  2. Refresh the page
  3. Check the logs (cmd)
GET / 500 in 179ms
 ⨯ {
  name: 'IllegalStateException',
  message: 'Trying to load a browser-only module on non-browser environment',
  digest: '2501484275'
}

Current vs. Expected behavior

I was using next^14.2.3 without any issues, and my application was running smoothly. After upgrading to next^14.2.8, I started encountering the mentioned error. Although the application still works fine, every time I refresh the page, error logs appear in the command line.

image

Provide environment information

Operating System:
  Platform: win32
  Arch: x64
  Version: Windows 10 Enterprise LTSC 2021
  Available memory (MB): 16197
  Available CPU cores: 8
Binaries:
  Node: 18.17.0
  npm: N/A
  Yarn: N/A
  pnpm: N/A
Relevant Packages:
  next: 14.2.8 // Latest available version is detected (14.2.8).
  eslint-config-next: 14.2.8
  react: 18.3.1
  react-dom: 18.3.1
  typescript: 5.4.5
Next.js Config:
  output: N/A

Which area(s) are affected? (Select all that apply)

Lazy Loading, Middleware, Runtime

Which stage(s) are affected? (Select all that apply)

next dev (local), next start (local)

Additional context

No response

github-actions[bot] commented 1 month ago

We could not detect a valid reproduction link. Make sure to follow the bug report template carefully.

Why was this issue closed?

To be able to investigate, we need access to a reproduction to identify what triggered the issue. We need a link to a public GitHub repository (template for App Router, template for Pages Router), but you can also use these templates: CodeSandbox: App Router or CodeSandbox: Pages Router.

The bug template that you filled out has a section called "Link to the code that reproduces this issue", which is where you should provide the link to the reproduction.

What should I do?

Depending on the reason the issue was closed, you can do the following:

In general, assume that we should not go through a lengthy onboarding process at your company code only to be able to verify an issue.

My repository is private and cannot make it public

In most cases, a private repo will not be a sufficient minimal reproduction, as this codebase might contain a lot of unrelated parts that would make our investigation take longer. Please do not make it public. Instead, create a new repository using the templates above, adding the relevant code to reproduce the issue. Common things to look out for:

I did not open this issue, but it is relevant to me, what can I do to help?

Anyone experiencing the same issue is welcome to provide a minimal reproduction following the above steps by opening a new issue.

I think my reproduction is good enough, why aren't you looking into it quickly?

We look into every Next.js issue and constantly monitor open issues for new comments.

However, sometimes we might miss one or two due to the popularity/high traffic of the repository. We apologize, and kindly ask you to refrain from tagging core maintainers, as that will usually not result in increased priority.

Upvoting issues to show your interest will help us prioritize and address them as quickly as possible. That said, every issue is important to us, and if an issue gets closed by accident, we encourage you to open a new one linking to the old issue and we will look into it.

Useful Resources

lubieowoce commented 1 month ago

I believe your issue is the same as https://github.com/vercel/next.js/issues/69720. See this answer for an explanation https://github.com/vercel/next.js/issues/69720#issuecomment-2331689003

Also, next time please put this code in a github repo or a codesandbox