๐Ÿ“ฆ ronitrajfr / ayoni

๐Ÿ“„ route.ts ยท 91 lines
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91import { NextResponse, type NextRequest } from "next/server";
import { db } from "@/server/db";
import { headers } from "next/headers";
import { geolocation } from "@vercel/functions";

type Payload = {
  websiteId: string;
  url: string;
  referrer?: string;
  browser?: string;
  os?: string;
  deviceType?: string;
};

export async function POST(req: NextRequest) {
  try {
    const headersList = await headers();
    const ip = headersList.get("x-forwarded-for") ?? "unknown";

    const text = await req.text();
    const { websiteId, url, referrer, browser, os, deviceType } = JSON.parse(
      text,
    ) as Payload;

    const { country } = geolocation(req);

    if (!websiteId || !url) {
      return NextResponse.json({ error: "Invalid request" }, { status: 400 });
    }

    const website = await db.website.findUnique({ where: { id: websiteId } });

    if (!website) {
      return NextResponse.json({ error: "Website not found" }, { status: 404 });
    }
    const websiteUrl = website.domain;
    const NewUrl = new URL(url);
    console.log(NewUrl.host);
    console.log(websiteUrl);
    if (websiteUrl !== NewUrl.host) {
      return NextResponse.json({ error: "Invalid request" }, { status: 400 });
    }

    await db.pageView.create({
      data: {
        ip: ip !== "unknown" ? ip : null,
        websiteId,
        url,
        referrer,
        browser,
        os,
        country: country ?? null,
        deviceType,
      },
    });

    if (ip !== "unknown") {
      const existingVisitor = await db.uniqueVisitorLog.findUnique({
        where: {
          ip_websiteId: {
            ip,
            websiteId,
          },
        },
      });
      if (!existingVisitor) {
        await db.uniqueVisitorLog.create({
          data: {
            ip,
            websiteId,
            url,
            referrer,
            browser,
            os,
            country,
            deviceType,
          },
        });
      }
    }

    return NextResponse.json({ success: true }, { status: 200 });
  } catch (err) {
    console.error("Analytics error:", err);
    return NextResponse.json(
      { error: "Internal server error" },
      { status: 400 },
    );
  }
}