Google Analytics 4, con interruptor y respetando el consentimiento

Se añade GA4 (gtag.js) con el componente oficial `@next/third-parties`, que es lo
que recomienda el doc de Next 16 y carga el mismo gtag pero tras la hidratación.

DOS interruptores:
1. `NEXT_PUBLIC_GA_ID` en el .env (no versionado). Vacío o sin poner = no se carga
   nada. Documentada en el README.
2. El consentimiento del visitante. El sitio YA tenía un banner con la categoría
   «Analíticas» que se puede rechazar: soltar gtag en el <head> lo habría
   convertido en mentira, y con visitantes en la UE, en un problema legal.

Para lo segundo se expone `useConsent(categoría)` desde CookieConsent, que además
reacciona en caliente: `writeConsent`/`revokeConsent` ya disparaban el evento
`ns:consentchange`, así que la analítica entra en cuanto se acepta y desaparece
si se revoca, sin recargar. Arranca en `false` a propósito: hasta confirmar el
consentimiento no se carga nada.

Verificado en el build: sin consentimiento no hay ni rastro de googletagmanager
en el HTML, y la condición compilada es `id && consent ? <GoogleAnalytics/> : null`.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-07-15 19:49:00 +00:00
parent fbc17f2cf8
commit 94f9731b2c
6 changed files with 71 additions and 0 deletions
+18
View File
@@ -8,6 +8,7 @@
"name": "web-next",
"version": "0.1.0",
"dependencies": {
"@next/third-parties": "^16.2.10",
"@types/qrcode": "^1.5.6",
"iron-session": "^8.0.4",
"mysql2": "^3.22.6",
@@ -1575,6 +1576,18 @@
"node": ">= 10"
}
},
"node_modules/@next/third-parties": {
"version": "16.2.10",
"resolved": "https://registry.npmjs.org/@next/third-parties/-/third-parties-16.2.10.tgz",
"integrity": "sha512-H3yxCMLziM1JKXnjQv83WBH2cp1fB1vMxpC1/bBTpvvaesBEuRuprpzq5RI32atis0VhUZflgdpJdGNZIGpQaQ==",
"dependencies": {
"third-party-capital": "1.0.20"
},
"peerDependencies": {
"next": "^13.0.0 || ^14.0.0 || ^15.0.0 || ^16.0.0-beta.0",
"react": "^18.2.0 || 19.0.0-rc-de68d2f4-20241204 || ^19.0.0"
}
},
"node_modules/@nodelib/fs.scandir": {
"version": "2.1.5",
"resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz",
@@ -7484,6 +7497,11 @@
"url": "https://opencollective.com/webpack"
}
},
"node_modules/third-party-capital": {
"version": "1.0.20",
"resolved": "https://registry.npmjs.org/third-party-capital/-/third-party-capital-1.0.20.tgz",
"integrity": "sha512-oB7yIimd8SuGptespDAZnNkzIz+NWaJCu2RMsbs4Wmp9zSDUM8Nhi3s2OOcqYuv3mN4hitXc8DVx+LyUmbUDiA=="
},
"node_modules/tinyglobby": {
"version": "0.2.17",
"resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz",