Skip to content

Commit

Permalink
feat: /api/pageview capture ip and geo info (vercel)
Browse files Browse the repository at this point in the history
  • Loading branch information
duyet committed Jul 24, 2024
1 parent f089714 commit 3910c6a
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 0 deletions.
11 changes: 11 additions & 0 deletions app/api/pageview/route.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { getClient } from '@/lib/clickhouse'
import { normalizeUrl } from '@/lib/utils'
import { geolocation } from '@vercel/functions'
import type { NextRequest } from 'next/server'
import { NextResponse, userAgent } from 'next/server'

Expand All @@ -17,6 +18,12 @@ export async function GET(request: NextRequest) {
// https://nextjs.org/docs/app/api-reference/functions/userAgent
const ua = userAgent(request)

// https://vercel.com/guides/geo-ip-headers-geolocation-vercel-functions#further-reading
const { city, country, region } = geolocation(request)
const realIp = request.headers.get('x-real-ip') ?? ''
const forwardedFor = request.headers.get('x-forwarded-for') ?? realIp
const ip = (forwardedFor.split(',')[0] || '').trim()

try {
await client.insert({
table: 'system.monitoring_events',
Expand All @@ -33,6 +40,10 @@ export async function GET(request: NextRequest) {
engine: ua.engine,
cpu: ua.cpu,
isBot: ua.isBot,
ip,
city,
country,
region,
}),
},
],
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
"@tremor/react": "^3.15.0",
"@uiw/react-heat-map": "^2.2.1",
"@vercel/analytics": "^1.3.1",
"@vercel/functions": "^1.4.0",
"class-variance-authority": "^0.7.0",
"clsx": "^2.0.0",
"cmdk": "^1.0.0",
Expand Down
5 changes: 5 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -1930,6 +1930,11 @@
dependencies:
server-only "^0.0.1"

"@vercel/functions@^1.4.0":
version "1.4.0"
resolved "https://registry.yarnpkg.com/@vercel/functions/-/functions-1.4.0.tgz#76db3a213416425e600d302ef66d35f775e11fb7"
integrity sha512-Ln6SpIkms1UJg306X2kbEMyG9ol+mjDr2xx389cvsBxgFyFMI9Bm+LYOG4N3TSik4FI59MECyyc4oz7AIAYmqQ==

acorn-jsx@^5.3.2:
version "5.3.2"
resolved "https://registry.yarnpkg.com/acorn-jsx/-/acorn-jsx-5.3.2.tgz#7ed5bb55908b3b2f1bc55c6af1653bada7f07937"
Expand Down

0 comments on commit 3910c6a

Please sign in to comment.