fullstorydev / fullstory-browser-sdk

Official FullStory SDK for JavaScript, for web browsers
MIT License
55 stars 17 forks source link

Help : Docs for using it with Next.js #51

Closed marufMunshi closed 4 years ago

van-fs commented 4 years ago

Hi @marufMunshi , thanks for bringing this up. I've not experimented with Next.js but given it's from Zeit, I'm sure it's really cool. Did you run into anything that you found specifically challenging?

@patrick-fs looks like Next.js is doing a lot of SSR so the window is undefined. There are some suggestions on SO to rely on componentWillMount. Any guidance on how we might bridge the helloworld Next.js functional component seen below to load FullStory?

export default function Index() {

  return (
    <div>
      <p>Hello Next.js</p>
    </div>
  );
}
patrick-fs commented 4 years ago

Hi @marufMunshi and @van-fs. You can use React's useEffect hook to initialize FullStory in a Next.js functional component:

import { useEffect } from 'react';
import * as FullStory from '@fullstory/browser'

export default function Index() {
  useEffect(() => {
    FullStory.init({ orgId: '231'});
  }, []);
  return (
    <div>
      <p>Hello Next.js</p>
    </div>
  )
}

It will build as expected. Please be sure execute this hook in your root component (usually Index which bootstraps App) so that FullStory is initialized as soon as possible during run time.

marufMunshi commented 4 years ago

thanks, @patrick-fs. I used FullStory with Next.js in a different way.

// _document.js
import Document, { Html, Head, Main, NextScript } from "next/document";

class MyDocument extends Document {
  static async getInitialProps(ctx) {
    const initialProps = await Document.getInitialProps(ctx);
    return { ...initialProps };
  }

  renderFullstorySnippet() {
    // return FullStory snippet found in dashboard as string
  }

  render() {
    return (
      <Html>
        <Head>
          <script
            dangerouslySetInnerHTML={{ __html: this.renderFullstorySnippet() }}
          />
        </Head>
        <body>
          <Main />
          <NextScript />
        </body>
      </Html>
    );
  }
}

export default MyDocument;

https://nextjs.org/docs/advanced-features/custom-document