- Refactored Google Analytics proxy routes in the Next.js configuration to enhance fallback handling. - Improved fetch interception logic in the RootLayout component for more robust handling of Google Analytics requests, including support for `sendBeacon`. - Updated the analytics script source to align with new API routes for better tracking accuracy.
66 lines
1.9 KiB
TypeScript
66 lines
1.9 KiB
TypeScript
import { NextRequest, NextResponse } from 'next/server';
|
|
|
|
export async function GET(request: NextRequest) {
|
|
const searchParams = request.nextUrl.searchParams;
|
|
const url = new URL('https://www.google-analytics.com/g/collect');
|
|
|
|
// Copiar todos os parâmetros da query string
|
|
searchParams.forEach((value, key) => {
|
|
url.searchParams.append(key, value);
|
|
});
|
|
|
|
try {
|
|
const response = await fetch(url.toString(), {
|
|
method: 'GET',
|
|
headers: {
|
|
'User-Agent': request.headers.get('user-agent') || '',
|
|
'Accept-Language': request.headers.get('accept-language') || '',
|
|
},
|
|
});
|
|
|
|
return new NextResponse(null, {
|
|
status: response.status,
|
|
headers: {
|
|
'Cache-Control': 'no-cache, no-store, must-revalidate',
|
|
},
|
|
});
|
|
} catch (error) {
|
|
console.error('Google Analytics proxy error:', error);
|
|
return new NextResponse(null, { status: 200 }); // Retornar 200 para não quebrar o tracking
|
|
}
|
|
}
|
|
|
|
export async function POST(request: NextRequest) {
|
|
const searchParams = request.nextUrl.searchParams;
|
|
const url = new URL('https://www.google-analytics.com/g/collect');
|
|
|
|
// Copiar todos os parâmetros da query string
|
|
searchParams.forEach((value, key) => {
|
|
url.searchParams.append(key, value);
|
|
});
|
|
|
|
try {
|
|
const body = await request.text();
|
|
|
|
const response = await fetch(url.toString(), {
|
|
method: 'POST',
|
|
headers: {
|
|
'User-Agent': request.headers.get('user-agent') || '',
|
|
'Accept-Language': request.headers.get('accept-language') || '',
|
|
'Content-Type': 'text/plain',
|
|
},
|
|
body: body || undefined,
|
|
});
|
|
|
|
return new NextResponse(null, {
|
|
status: response.status,
|
|
headers: {
|
|
'Cache-Control': 'no-cache, no-store, must-revalidate',
|
|
},
|
|
});
|
|
} catch (error) {
|
|
console.error('Google Analytics proxy error:', error);
|
|
return new NextResponse(null, { status: 200 });
|
|
}
|
|
}
|