Skip to content

AnalyticsBrowser.load returns a Promise (@segment/analytics-next) #1269

@SameeraMadushan

Description

@SameeraMadushan

I am using @segment/analytics-next in my Next.js project, and I noticed that the AnalyticsBrowser.load method returns a promise.
However, this behavior is not clearly documented in the official documentation or the example project provided by Segment or Vercel.

Here is the relevant code snippet from my project:

import { AnalyticsBrowser } from "@segment/analytics-next";

export const analytics = AnalyticsBrowser.load({
  writeKey: process.env.NEXT_PUBLIC_SEGMENT_KEY
}).catch(err => console.error(err));

export const page = () => {
  analytics.page(); // This fails if the promise is not resolved 
};

Issue:

  1. The AnalyticsBrowser.load method returns a promise, but this is not mentioned in the documentation or the example project.
  2. If the promise is not handled correctly, it can lead to runtime errors because the analytics object is not initialized before calling methods like page, identify, or track.
  3. This behavior is confusing for developers who expect AnalyticsBrowser.load to return a fully initialized analytics object synchronously.

Steps to Reproduce:

  1. Use the AnalyticsBrowser.load method as shown in the example project or documentation.
  2. Attempt to call analytics.page() or other methods immediately after AnalyticsBrowser.load.
  3. Observe that the analytics object is not initialized, leading to runtime errors.

Expected Behavior:

The documentation and example project should clearly state that AnalyticsBrowser.load returns a promise and provide guidance on how to handle it properly.

Actual Behavior:

The documentation and example project do not mention that AnalyticsBrowser.load returns a promise, leading to confusion and potential runtime errors.

Suggested Fix:

  1. Update the documentation to explicitly mention that AnalyticsBrowser.load returns a promise.
  2. Update the example project to handle the promise correctly. For example:
import { AnalyticsBrowser } from "@segment/analytics-next";

const analyticsPromise = AnalyticsBrowser.load({
  writeKey: process.env.NEXT_PUBLIC_SEGMENT_KEY
});

analyticsPromise.then(([analytics]) => {
  analytics.page();
  analytics.track("Test Event", { foo: "bar" });
});
  1. Provide examples of how to handle the promise in real-world scenarios, such as in a Next.js app with server-side rendering or client-side hydration.

Environment:

Library: @segment/analytics-next
Version: 1.78.1
Framework: Next.js 14
Node.js Version: 23.10.0

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions