Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trouble setting up Segment with Next.js

I've been trying to just integrate Segment with Next.js, and I'm not sure why inserting the shippet into the Head isn't working. For some reason Next.js doesn't understand the syntax of adding a <script> into the head like this:

export default function Head() {
  return (
    <>
      <title></title>
      <meta content="width=device-width, initial-scale=1" name="viewport" />
      <link rel="icon" href="/favicon.ico" />
      <script>
  !function(){var analytics=window.analytics=window.analytics||[];if(!analytics.initialize)if(analytics.invoked)window.console&&console.error&&console.error("Segment snippet included twice.");else{analytics.invoked=!0;analytics.methods=["trackSubmit","trackClick","trackLink","trackForm","pageview","identify","reset","group","track","ready","alias","debug","page","once","off","on","addSourceMiddleware","addIntegrationMiddleware","setAnonymousId","addDestinationMiddleware"];analytics.factory=function(e){return function(){var t=Array.prototype.slice.call(arguments);t.unshift(e);analytics.push(t);return analytics}};for(var e=0;e<analytics.methods.length;e++){var key=analytics.methods[e];analytics[key]=analytics.factory(key)}analytics.load=function(key,e){var t=document.createElement("script");t.type="text/javascript";t.async=!0;t.src="https://cdn.segment.com/analytics.js/v1/" + key + "/analytics.min.js";var n=document.getElementsByTagName("script")[0];n.parentNode.insertBefore(t,n);analytics._loadOptions=e};analytics._writeKey="WRITE_KEY";;analytics.SNIPPET_VERSION="4.15.3";
  analytics.load("WRITE_KEY");
  analytics.page();
  }}();
</script>
    </>
  )
}

This gives me errors.

I tried to use this example with @segment/snippet to load Segment, but it also doesn't seem to work as expected.

Am I missing something?

like image 352
Holden Avatar asked Oct 18 '25 15:10

Holden


1 Answers

Segment.io team relase an example with a nextjs integration [1]

import { AnalyticsBrowser } from '@segment/analytics-next'

const AnalyticsContext = React.createContext<AnalyticsBrowser>(undefined!);

type Props = {
  writeKey: string;
  children: React.ReactNode;
};
export const AnalyticsProvider = ({ children, writeKey }: Props) => {
  const analytics = React.useMemo(
    () => AnalyticsBrowser.load({ writeKey }),
    [writeKey]
  );
  return (
    <AnalyticsContext.Provider value={analytics}>
      {children}
    </AnalyticsContext.Provider>
  );
};

// Create an analytics hook that we can use with other components.
export const useAnalytics = () => {
  const result = React.useContext(AnalyticsContext);
  if (!result) {
    throw new Error("Context used outside of its Provider!");
  }
  return result;
};

// use the context we just created...
const TrackButton = () => {
  const analytics = useAnalytics()
  return (
    <button onClick={() => analytics.track('hello world')}>
      Track!
    </button>
  )
}

const App = () => {
  return (
    <AnalyticsProvider writeKey='<YOUR_WRITE_KEY>'>
      <TrackButton />
    </AnalyticsProvider>
  )

I integrate this with my segment key and works like a charm.

[1] https://github.com/segmentio/analytics-next/tree/master/packages/browser


Edit: It seems they leave the hook version for something more object-oriented [2]

should work as previous v [2] https://github.com/segmentio/analytics-next/tree/master/packages/browser#nextjs

like image 93
vmariano Avatar answered Oct 20 '25 07:10

vmariano



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!