Files
portifolio-evandrodevbr/app/api/gtm/[id]/route.ts
T
Evandro Fonseca Junior c9b057b674 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.
2026-01-20 21:10:39 -03:00

48 lines
1.2 KiB
TypeScript

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 });
}
}