- Changed the parameter type in the GET function to a promise, ensuring proper resolution of the `id` before use. - Improved error handling by awaiting the parameters, enhancing the robustness of the API route.
48 lines
1.2 KiB
TypeScript
48 lines
1.2 KiB
TypeScript
import { NextRequest, NextResponse } from 'next/server';
|
|
|
|
export async function GET(
|
|
request: NextRequest,
|
|
{ params }: { params: Promise<{ id: string }> }
|
|
) {
|
|
const { id } = await 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 });
|
|
}
|
|
}
|