|
| 1 | +import { NextURL } from 'next/dist/server/web/next-url' |
| 2 | +import { notFound } from 'next/navigation' |
| 3 | +import { NextRequest, NextResponse, userAgent } from 'next/server' |
| 4 | +import { v4 as uuidv4 } from 'uuid' |
| 5 | + |
| 6 | +type UserAgent = { |
| 7 | + device: string | undefined |
| 8 | + os: string | undefined |
| 9 | + browser: string | undefined |
| 10 | +} |
| 11 | + |
| 12 | +type SplittedUrl = { |
| 13 | + domain: string |
| 14 | + subdomain: string | undefined |
| 15 | + path: string |
| 16 | +} |
| 17 | + |
| 18 | +const splitUrl = (url: NextURL): SplittedUrl => { |
| 19 | + const domain = url.hostname |
| 20 | + const subdomain = domain.split('.').slice(0, -2).join('.') ?? undefined |
| 21 | + const path = url.pathname |
| 22 | + return { domain, subdomain, path } |
| 23 | +} |
| 24 | + |
| 25 | +const sendAnalytics = async ( |
| 26 | + agent: UserAgent, |
| 27 | + userKey: string, |
| 28 | + urlParts: SplittedUrl |
| 29 | +) => { |
| 30 | + const body = JSON.stringify({ ...agent, ...urlParts, userKey }) |
| 31 | + fetch(`${process.env.BACKEND_URL}/analytics`, {body, method: "POST"}) |
| 32 | +} |
| 33 | + |
| 34 | +export default async function middleware(request: NextRequest) { |
| 35 | + const urlParts = splitUrl(request.nextUrl) |
| 36 | + const response = NextResponse.next() |
| 37 | + const userKey = request.cookies.get('userKey')?.value ?? uuidv4() |
| 38 | + response.cookies.set('userKey', userKey) |
| 39 | + |
| 40 | + const { device, os, browser, isBot } = userAgent(request) |
| 41 | + if (isBot) notFound() |
| 42 | + await sendAnalytics( |
| 43 | + { device: device.model, os: os.name, browser: browser.name }, |
| 44 | + userKey, |
| 45 | + urlParts |
| 46 | + ) |
| 47 | + return response |
| 48 | +} |
| 49 | + |
| 50 | +export const config = { |
| 51 | + matcher: ['/:path'], |
| 52 | +} |
0 commit comments