reapziq / next-yandex-metrica

Yandex Metrica integration for Next.js
MIT License
19 stars 2 forks source link

/app folder, build fails in a backend api route #13

Closed di-sukharev closed 5 months ago

di-sukharev commented 5 months ago

i use latest nextjs with the /app folder, can i call ym(id, "reachGoal", "smth") in a backend app route e.g. /app/api/metrics/route.ts? build fails when i call the ym(.....) in such an api route with this error, looks like it thinks it's a page:

> Build error occurred
Error: Failed to collect page data for /api/bot
    at /node_modules/next/dist/build/utils.js:1217:15
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
  type: 'Error'
}
   Creating an optimized production build  .   Collecting page data  .error: script "build" exited with code 1

here is my function:

import { db } from "@/prisma/pool";
import { ym } from "next-yandex-metrica";

export async function reachGoal(goal: string, tgId?: string | number) {
  try {
    const user = await db.user.findUnique({
      where: {
        tgId: String(tgId),
      },
      select: {
        tgId: true,
        startParam: true,
      },
    });

    const options = user
      ? {
          params: {
            tgId: user.tgId,
            startParam: user.startParam,
          },
          userParams: {
            tgId: user.tgId,
            startParam: user.startParam,
          },
        }
      : undefined;

    ym(
      Number(process.env.NEXT_PUBLIC_YANDEX_METRICS_ID!),
      "reachGoal",
      goal,
      options
    );
    console.log("LOG_YM_REACH_GOAL", goal);
  } catch (error) {
    console.error("CANT_LOG_YM_REACH_GOAL", goal, error);
  }
}

i then import it in e.g. app/api/any_file.ts like import { reachGoal } from "@/lib/yandex-metrics/reactGoal"; and it fails with the error when i run next build

di-sukharev commented 5 months ago

ok, i see, it's only running with the window being around https://github.com/reapziq/next-yandex-metrica/blob/main/src/lib/ym.ts

how can i call a setGoal from in a backend endpoint?

reapziq commented 5 months ago

Hi! As far as I'm aware, Yandex Metrica does not provide any external API documentation, leaving communication through the JS Tag API as the sole documented option. However, you can use something like Plausible Analytics Events API as an alternative.

di-sukharev commented 5 months ago

thanks <3