Blog>
Snippets

Server-Side Analytics with Next.js 14 and Segment

Setup server-side analytics in Next.js 14 using Segment to capture data from both the client and server.
import { Analytics, AnalyticsBrowser } from '@segment/analytics-next';

export async function initSegmentAnalytics() {
  const analytics = await AnalyticsBrowser.load({ writeKey: 'YOUR_SEGMENT_WRITE_KEY' });
  return analytics;
}
Initializes the Segment analytics library on the client side. It asynchronously loads the AnalyticsBrowser module from '@segment/analytics-next' package. Replace 'YOUR_SEGMENT_WRITE_KEY' with the actual key provided by Segment.
import { Analytics } from '@segment/analytics-next';
import { createHttpClient } from '@segment/analytics-next/dist/pkg/browser-http-client';

export async function getServerSideAnalytics() {
  const httpClient = createHttpClient();
  const analytics = new Analytics({
    writeKey: 'YOUR_SEGMENT_WRITE_KEY',
    httpClient,
  });

  return analytics;
}
Sets up the Segment analytics to be used server-side in Next.js. It imports the necessary modules and initializes `Analytics` with an HTTP client. This allows for server-side tracking. Replace 'YOUR_SEGMENT_WRITE_KEY' with your Segment workspace `writeKey`.
export async function trackEvent(event, user, analytics) {
  try {
    await analytics.track({
      event: event.name,
      userId: user.id,
      properties: event.properties
    });
    console.log(`Event tracked: ${event.name}`);
  } catch (error) {
    console.error(`Error tracking event ${event.name}:`, error);
  }
}
This function takes in an event object and a user object, and uses the Segment Analytics instance to track the event. It logs a message on successful tracking and an error if it fails.
export default async function handler(req, res) {
  const analytics = await getServerSideAnalytics();
  const user = { id: req.userId };
  const event = { name: 'Server-side Event', properties: { foo: 'bar' } };

  await trackEvent(event, user, analytics);

  res.status(200).json({ message: 'Event tracked server-side' });
}
An example of a Next.js API route handler which integrates server-side tracking using Segment. It takes the request object to fetch user data, defines an example event, tracks it by calling `trackEvent`, and responds with a success message.