Blog>
Snippets

Using Next.js API Routes for Event Tracking

Use an API route in Next.js 14 to track custom events and send them to an analytics endpoint, ensuring server-side data privacy.
// pages/api/track-event.js
import axios from 'axios';

export default async function handler(req, res) {
  if (req.method === 'POST') {
    // Replace with your analytics endpoint
    const analyticsEndpoint = 'https://youranalytics.endpoint/track';
    const { eventName, eventData } = req.body;

    try {
      // Send event data to your analytics server
      await axios.post(analyticsEndpoint, {
        eventName,
        eventData
      });
      // Respond with a success status code
      res.status(200).json({ success: true });
    } catch (error) {
      // Handle any errors
      console.error('Event tracking failed', error);
      res.status(500).json({ success: false, error: 'Event tracking failed' });
    }
  } else {
    // Handle unsupported method
    res.setHeader('Allow', ['POST']);
    res.status(405).end(`Method ${req.method} Not Allowed`);
  }
}
This is an API route in Next.js that handles POST requests to track events. It extracts the event name and data from the request body and sends it to an analytics endpoint. Appropriate success or error responses are sent back to the client.
// pages/_app.js or anywhere in your client-side code
import axios from 'axios';

// Example function to call the API route
async function trackEvent(eventName, eventData) {
  try {
    // Call the Next.js API Route
    await axios.post('/api/track-event', {
      eventName,
      eventData
    });
    console.log('Event tracked successfully');
  } catch (error) {
    // Handle any errors in event tracking
    console.error('Event tracking error:', error);
  }
}
This example function can be called from the client-side to track an event. It sends a POST request to the Next.js API route '/api/track-event' with the event details. Console logs are used to verify that the event was tracked successfully or log errors.