Search code examples
next.jsgoogle-analytics-apinext.js13swr

API route not found on NextJS 14 (App/route)


I want to use the Google Analytics API using SWR on Next.js 1, however the route returns 404.

const { data: visitors } = useSWR("/api/dash/route", fetcher);

My folders tree:

enter image description here

app/analytics/page.tsx

"use client";
import useSWR from "swr";
import fetcher from "@lib/fetcher";

export default function Analytics() {
  const { data: visitors } = useSWR("/api/dash/route", fetcher);
  return (
      <div>{visitors?.totalVisitors} {visitors?.days} days</div>
  );
}

src/app/api/dash/route.ts

import { NextApiRequest, NextApiResponse } from "next";
import { BetaAnalyticsDataClient } from "@google-analytics/data";

const propertyId = process.env.GA_PROPERTY_ID;
const DAYS = 7;

const analyticsDataClient = new BetaAnalyticsDataClient({
  credentials: {
    client_email: process.env.GA_CLIENT_EMAIL,
    private_key: process.env.GA_PRIVATE_KEY?.replace(/\n/gm, '\n'),
  },
});

export default async function handler(
  _req: NextApiRequest,
  res: NextApiResponse
) {
  const [response] = await analyticsDataClient.runReport({
    property: `properties/${propertyId}`,
    dateRanges: [
      {
        startDate: `${DAYS}daysAgo`,
        endDate: "today",
      },
    ],
    dimensions: [
      {
        name: "year",
      },
    ],
    metrics: [
      {
        name: "activeUsers",
      },
    ],
  });

  let totalVisitors = 0;
  response.rows?.forEach((row: any) => {
    totalVisitors += parseInt(row.metricValues[0].value);
  });

  res.setHeader(
    "Cache-Control",
    "public, s-maxage=43200, stale-while-revalidate=21600"
  );

  return res.status(200).json({
    totalVisitors,
    days: 7,
  });
}

I've tried everything:

  • Change name to "route.ts" / "ga.ts" / "route.js"
  • I've already tried putting "api/route.ts" in the path
  • I've already tried calling the api with "http://localhost:3000/api/dash/route", "/api/dash/route", "api/dash/route", "./api/dash/route"
  • use the code on components

On browser console:

enter image description here


Solution

  • Try this:

    Instead of making a request to http://localhost:3000/api/dash/route make a request to http://localhost:3000/api/dash

    Don't change the file structure.

    Check this sandbox and try to hit the api/dash route.