feat(analytics): update Google Analytics integration and improve fetch interception
- 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.
This commit is contained in:
1 parent
ad6a76efdd
commit
c9b057b674
4 files changed
+154
-19
No files matched your search
@@ -0,0 +1,65 @@
|
||||
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 });
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user