Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Prevent amplitude import in server-side rendering environment #212

Closed
jhlee910609 opened this issue Sep 25, 2021 · 7 comments
Closed

Prevent amplitude import in server-side rendering environment #212

jhlee910609 opened this issue Sep 25, 2021 · 7 comments
Labels
stale automatically marked as stale because it has not had recent activity.

Comments

@jhlee910609
Copy link
Contributor

jhlee910609 commented Sep 25, 2021

image

문제

  • npm에 publish된 0.2.0 version 기준입니다.
  • Server-Side-Rendering(이하 SSR) 환경에서 window 객체가 없어 amplitude 관련 모듈이 정상 동작하지 않습니다.
  • amplitude 공식 문서에 따르면 SSR에서 event tracking 하고 싶으면 직접 amplitude 측에서 제공해주는 api로 관련 정보를 보내라고 언급되어 있습니다.
    • 많은 이들이 같은 문제를 겪고 있었습니다. 😢

해결책

  • SSR 환경에서 import 되지 않도록 합니다.
  • 혹은 amplitude 관련 모듈 및 util function들을 제거하고, 사용자가 알아서 사용하도록 합니다.
@jhlee910609 jhlee910609 changed the title amplitude SSR에서 module import 되지 않도록 막기 amplitude module 제거하기 (혹은 브라우저가 아닌 환경에서 import 되지 않도록 막기) Sep 25, 2021
@jhlee910609
Copy link
Contributor Author

jhlee910609 commented Sep 25, 2021

@milooy
Copy link
Member

milooy commented Sep 26, 2021

요런식으로 하면 돼요!

export const useInitAmplitude = ({ onInit }: { onInit(): void }) => {
  useEffect(() => {
    if (typeof window !== undefined) {
      import('amplitude-js')
        .then((ampPackage) => {
          amplitudeInstance = ampPackage.getInstance();
          amplitudeInstance.init(process.env.NEXT_PUBLIC_AMPLITUDE_KEY as string);
          onInit();
        })
        .catch(() => null);
    }
  }, []);
};

@jhlee910609
Copy link
Contributor Author

jhlee910609 commented Sep 26, 2021

@milooy 제가 가져가서 한번 해볼게요. 저희 프로젝트에 SSR 판단하는 util 함수가 존재하는데, 그거 사용해서 해보겠슴당~

@jhlee910609 jhlee910609 changed the title amplitude module 제거하기 (혹은 브라우저가 아닌 환경에서 import 되지 않도록 막기) Prevent amplitude import in server-side rendering environment Sep 26, 2021
@jhlee910609 jhlee910609 self-assigned this Sep 26, 2021
@jhlee910609
Copy link
Contributor Author

jhlee910609 commented Sep 26, 2021

@milooy
근데 amplitude initialize 함수가 아래와 같이 일반 ts file에 선언되어 있는 함수(amplitudeHelper 함수)인데, react-hook으로 감싸줘야하는 특별한 이유(의도하신 바)가 있나요? 👀 특별한 이유가 없다면 useEffect callback 로직만 구현해줘도 되지 않을까 싶어서요~

+) 추가적으로 initialize 함수에 console.warn 출력해주고, amplitude SSR 관련 문서 혹은 핸드북 링크 걸어주면 좋을 것 같습니다. SSR에서 사용할 거면 다른 방식 사용 유도를 위해서요.

import amplitude, {AmplitudeClient, Config} from 'amplitude-js';

export const initialize = (
  apiKey: string,
  userId?: string,
  config?: Config,
  callback?: (client: AmplitudeClient) => void,
) => {
  // eslint-disable-next-line import/no-named-as-default-member
  amplitude.getInstance().init(apiKey, userId, config, callback);
};

@jhlee910609 jhlee910609 removed their assignment Oct 3, 2021
@milooy
Copy link
Member

milooy commented Oct 10, 2021

제가 첨부한 코드는
SSR에 따라 amplitude 패키지 import여부부터 결정하는 코드예요~ (개인플젝에서 구현해뒀던거 그대로 복붙해옴)
저희상황에 맞게 변경해서 쓰면 됩니다.

위에서 useEffect만 빼도 되지 않을까요?

@milooy
Copy link
Member

milooy commented Oct 10, 2021

위 언급된 코드에 Fix 올렸습니다~

@stale
Copy link

stale bot commented Dec 9, 2021

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

@stale stale bot added the stale automatically marked as stale because it has not had recent activity. label Dec 9, 2021
@stale stale bot closed this as completed Dec 16, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
stale automatically marked as stale because it has not had recent activity.
Projects
None yet
Development

No branches or pull requests

2 participants