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:
Evandro Fonseca Junior committed 2026-01-20 21:10:39 -03:00
1 parent ad6a76efdd
commit c9b057b674
4 files changed
+154 -19

No files matched your search

+47
View File
@@ -0,0 +1,47 @@
import { NextRequest, NextResponse } from 'next/server';
export async function GET(
request: NextRequest,
{ params }: { params: { id: string } }
) {
const { id } = params;
try {
const response = await fetch(
`https://www.googletagmanager.com/gtag/js?id=${id}`,
{
headers: {
'User-Agent': request.headers.get('user-agent') || '',
},
}
);
if (!response.ok) {
return new NextResponse('Script not found', { status: 404 });
}
const scriptContent = await response.text();
// Modificar URLs internas do script para usar o proxy
const modifiedScript = scriptContent
.replace(
/https?:\/\/[^\/]*google-analytics\.com\/g\/collect/g,
'/api/metrics'
)
.replace(
/https?:\/\/[^\/]*google-analytics\.com/g,
'/api/metrics'
);
return new NextResponse(modifiedScript, {
status: 200,
headers: {
'Content-Type': 'application/javascript',
'Cache-Control': 'public, max-age=3600',
},
});
} catch (error) {
console.error('GTM proxy error:', error);
return new NextResponse('Proxy error', { status: 500 });
}
}