mirror of https://github.com/langgenius/dify.git
feat: integrate Google Analytics event tracking and update CSP for script sources (#30365)
Co-authored-by: CodingOnStar <hanxujiang@dify.ai>
This commit is contained in:
parent
bf76f10653
commit
6ca44eea28
|
|
@ -1,14 +1,18 @@
|
||||||
'use client'
|
'use client'
|
||||||
|
|
||||||
import type { ReactNode } from 'react'
|
import type { ReactNode } from 'react'
|
||||||
|
import Cookies from 'js-cookie'
|
||||||
import { usePathname, useRouter, useSearchParams } from 'next/navigation'
|
import { usePathname, useRouter, useSearchParams } from 'next/navigation'
|
||||||
|
import { parseAsString, useQueryState } from 'nuqs'
|
||||||
import { useCallback, useEffect, useState } from 'react'
|
import { useCallback, useEffect, useState } from 'react'
|
||||||
import {
|
import {
|
||||||
EDUCATION_VERIFY_URL_SEARCHPARAMS_ACTION,
|
EDUCATION_VERIFY_URL_SEARCHPARAMS_ACTION,
|
||||||
EDUCATION_VERIFYING_LOCALSTORAGE_ITEM,
|
EDUCATION_VERIFYING_LOCALSTORAGE_ITEM,
|
||||||
} from '@/app/education-apply/constants'
|
} from '@/app/education-apply/constants'
|
||||||
import { fetchSetupStatus } from '@/service/common'
|
import { fetchSetupStatus } from '@/service/common'
|
||||||
|
import { sendGAEvent } from '@/utils/gtag'
|
||||||
import { resolvePostLoginRedirect } from '../signin/utils/post-login-redirect'
|
import { resolvePostLoginRedirect } from '../signin/utils/post-login-redirect'
|
||||||
|
import { trackEvent } from './base/amplitude'
|
||||||
|
|
||||||
type AppInitializerProps = {
|
type AppInitializerProps = {
|
||||||
children: ReactNode
|
children: ReactNode
|
||||||
|
|
@ -22,6 +26,10 @@ export const AppInitializer = ({
|
||||||
// Tokens are now stored in cookies, no need to check localStorage
|
// Tokens are now stored in cookies, no need to check localStorage
|
||||||
const pathname = usePathname()
|
const pathname = usePathname()
|
||||||
const [init, setInit] = useState(false)
|
const [init, setInit] = useState(false)
|
||||||
|
const [oauthNewUser, setOauthNewUser] = useQueryState(
|
||||||
|
'oauth_new_user',
|
||||||
|
parseAsString.withOptions({ history: 'replace' }),
|
||||||
|
)
|
||||||
|
|
||||||
const isSetupFinished = useCallback(async () => {
|
const isSetupFinished = useCallback(async () => {
|
||||||
try {
|
try {
|
||||||
|
|
@ -45,6 +53,34 @@ export const AppInitializer = ({
|
||||||
(async () => {
|
(async () => {
|
||||||
const action = searchParams.get('action')
|
const action = searchParams.get('action')
|
||||||
|
|
||||||
|
if (oauthNewUser === 'true') {
|
||||||
|
let utmInfo = null
|
||||||
|
const utmInfoStr = Cookies.get('utm_info')
|
||||||
|
if (utmInfoStr) {
|
||||||
|
try {
|
||||||
|
utmInfo = JSON.parse(utmInfoStr)
|
||||||
|
}
|
||||||
|
catch (e) {
|
||||||
|
console.error('Failed to parse utm_info cookie:', e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Track registration event with UTM params
|
||||||
|
trackEvent(utmInfo ? 'user_registration_success_with_utm' : 'user_registration_success', {
|
||||||
|
method: 'oauth',
|
||||||
|
...utmInfo,
|
||||||
|
})
|
||||||
|
|
||||||
|
sendGAEvent(utmInfo ? 'user_registration_success_with_utm' : 'user_registration_success', {
|
||||||
|
method: 'oauth',
|
||||||
|
...utmInfo,
|
||||||
|
})
|
||||||
|
|
||||||
|
// Clean up: remove utm_info cookie and URL params
|
||||||
|
Cookies.remove('utm_info')
|
||||||
|
setOauthNewUser(null)
|
||||||
|
}
|
||||||
|
|
||||||
if (action === EDUCATION_VERIFY_URL_SEARCHPARAMS_ACTION)
|
if (action === EDUCATION_VERIFY_URL_SEARCHPARAMS_ACTION)
|
||||||
localStorage.setItem(EDUCATION_VERIFYING_LOCALSTORAGE_ITEM, 'yes')
|
localStorage.setItem(EDUCATION_VERIFYING_LOCALSTORAGE_ITEM, 'yes')
|
||||||
|
|
||||||
|
|
@ -67,7 +103,7 @@ export const AppInitializer = ({
|
||||||
router.replace('/signin')
|
router.replace('/signin')
|
||||||
}
|
}
|
||||||
})()
|
})()
|
||||||
}, [isSetupFinished, router, pathname, searchParams])
|
}, [isSetupFinished, router, pathname, searchParams, oauthNewUser, setOauthNewUser])
|
||||||
|
|
||||||
return init ? children : null
|
return init ? children : null
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -68,6 +68,7 @@ const AmplitudeProvider: FC<IAmplitudeProps> = ({
|
||||||
pageViews: true,
|
pageViews: true,
|
||||||
formInteractions: true,
|
formInteractions: true,
|
||||||
fileDownloads: true,
|
fileDownloads: true,
|
||||||
|
attribution: true,
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,3 +1,4 @@
|
||||||
|
import type { UnsafeUnwrappedHeaders } from 'next/headers'
|
||||||
import type { FC } from 'react'
|
import type { FC } from 'react'
|
||||||
import { headers } from 'next/headers'
|
import { headers } from 'next/headers'
|
||||||
import Script from 'next/script'
|
import Script from 'next/script'
|
||||||
|
|
@ -18,45 +19,54 @@ export type IGAProps = {
|
||||||
gaType: GaType
|
gaType: GaType
|
||||||
}
|
}
|
||||||
|
|
||||||
const GA: FC<IGAProps> = async ({
|
const extractNonceFromCSP = (cspHeader: string | null): string | undefined => {
|
||||||
|
if (!cspHeader)
|
||||||
|
return undefined
|
||||||
|
const nonceMatch = cspHeader.match(/'nonce-([^']+)'/)
|
||||||
|
return nonceMatch ? nonceMatch[1] : undefined
|
||||||
|
}
|
||||||
|
|
||||||
|
const GA: FC<IGAProps> = ({
|
||||||
gaType,
|
gaType,
|
||||||
}) => {
|
}) => {
|
||||||
if (IS_CE_EDITION)
|
if (IS_CE_EDITION)
|
||||||
return null
|
return null
|
||||||
|
|
||||||
const nonce = process.env.NODE_ENV === 'production' ? (await headers()).get('x-nonce') ?? '' : ''
|
const cspHeader = process.env.NODE_ENV === 'production'
|
||||||
|
? (headers() as unknown as UnsafeUnwrappedHeaders).get('content-security-policy')
|
||||||
|
: null
|
||||||
|
const nonce = extractNonceFromCSP(cspHeader)
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<Script
|
{/* Initialize dataLayer first */}
|
||||||
strategy="beforeInteractive"
|
|
||||||
async
|
|
||||||
src={`https://www.googletagmanager.com/gtag/js?id=${gaIdMaps[gaType]}`}
|
|
||||||
nonce={nonce ?? undefined}
|
|
||||||
>
|
|
||||||
</Script>
|
|
||||||
<Script
|
<Script
|
||||||
id="ga-init"
|
id="ga-init"
|
||||||
|
strategy="afterInteractive"
|
||||||
dangerouslySetInnerHTML={{
|
dangerouslySetInnerHTML={{
|
||||||
__html: `
|
__html: `
|
||||||
window.dataLayer = window.dataLayer || [];
|
window.dataLayer = window.dataLayer || [];
|
||||||
function gtag(){dataLayer.push(arguments);}
|
window.gtag = function gtag(){window.dataLayer.push(arguments);};
|
||||||
gtag('js', new Date());
|
window.gtag('js', new Date());
|
||||||
gtag('config', '${gaIdMaps[gaType]}');
|
window.gtag('config', '${gaIdMaps[gaType]}');
|
||||||
`,
|
`,
|
||||||
}}
|
}}
|
||||||
nonce={nonce ?? undefined}
|
nonce={nonce}
|
||||||
>
|
/>
|
||||||
</Script>
|
{/* Load GA script */}
|
||||||
|
<Script
|
||||||
|
strategy="afterInteractive"
|
||||||
|
src={`https://www.googletagmanager.com/gtag/js?id=${gaIdMaps[gaType]}`}
|
||||||
|
nonce={nonce}
|
||||||
|
/>
|
||||||
{/* Cookie banner */}
|
{/* Cookie banner */}
|
||||||
<Script
|
<Script
|
||||||
id="cookieyes"
|
id="cookieyes"
|
||||||
|
strategy="lazyOnload"
|
||||||
src="https://cdn-cookieyes.com/client_data/2a645945fcae53f8e025a2b1/script.js"
|
src="https://cdn-cookieyes.com/client_data/2a645945fcae53f8e025a2b1/script.js"
|
||||||
nonce={nonce ?? undefined}
|
nonce={nonce}
|
||||||
>
|
/>
|
||||||
</Script>
|
|
||||||
</>
|
</>
|
||||||
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
export default React.memo(GA)
|
export default React.memo(GA)
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,6 @@
|
||||||
'use client'
|
'use client'
|
||||||
import type { MailRegisterResponse } from '@/service/use-common'
|
import type { MailRegisterResponse } from '@/service/use-common'
|
||||||
|
import Cookies from 'js-cookie'
|
||||||
import { useRouter, useSearchParams } from 'next/navigation'
|
import { useRouter, useSearchParams } from 'next/navigation'
|
||||||
import { useCallback, useState } from 'react'
|
import { useCallback, useState } from 'react'
|
||||||
import { useTranslation } from 'react-i18next'
|
import { useTranslation } from 'react-i18next'
|
||||||
|
|
@ -10,6 +11,20 @@ import Toast from '@/app/components/base/toast'
|
||||||
import { validPassword } from '@/config'
|
import { validPassword } from '@/config'
|
||||||
import { useMailRegister } from '@/service/use-common'
|
import { useMailRegister } from '@/service/use-common'
|
||||||
import { cn } from '@/utils/classnames'
|
import { cn } from '@/utils/classnames'
|
||||||
|
import { sendGAEvent } from '@/utils/gtag'
|
||||||
|
|
||||||
|
const parseUtmInfo = () => {
|
||||||
|
const utmInfoStr = Cookies.get('utm_info')
|
||||||
|
if (!utmInfoStr)
|
||||||
|
return null
|
||||||
|
try {
|
||||||
|
return JSON.parse(utmInfoStr)
|
||||||
|
}
|
||||||
|
catch (e) {
|
||||||
|
console.error('Failed to parse utm_info cookie:', e)
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const ChangePasswordForm = () => {
|
const ChangePasswordForm = () => {
|
||||||
const { t } = useTranslation()
|
const { t } = useTranslation()
|
||||||
|
|
@ -55,11 +70,18 @@ const ChangePasswordForm = () => {
|
||||||
})
|
})
|
||||||
const { result } = res as MailRegisterResponse
|
const { result } = res as MailRegisterResponse
|
||||||
if (result === 'success') {
|
if (result === 'success') {
|
||||||
// Track registration success event
|
const utmInfo = parseUtmInfo()
|
||||||
trackEvent('user_registration_success', {
|
trackEvent(utmInfo ? 'user_registration_success_with_utm' : 'user_registration_success', {
|
||||||
method: 'email',
|
method: 'email',
|
||||||
|
...utmInfo,
|
||||||
})
|
})
|
||||||
|
|
||||||
|
sendGAEvent(utmInfo ? 'user_registration_success_with_utm' : 'user_registration_success', {
|
||||||
|
method: 'email',
|
||||||
|
...utmInfo,
|
||||||
|
})
|
||||||
|
Cookies.remove('utm_info') // Clean up: remove utm_info cookie
|
||||||
|
|
||||||
Toast.notify({
|
Toast.notify({
|
||||||
type: 'success',
|
type: 'success',
|
||||||
message: t('api.actionSuccess', { ns: 'common' }),
|
message: t('api.actionSuccess', { ns: 'common' }),
|
||||||
|
|
|
||||||
|
|
@ -9,4 +9,22 @@ declare module 'lamejs/src/js/Lame';
|
||||||
declare module 'lamejs/src/js/BitStream';
|
declare module 'lamejs/src/js/BitStream';
|
||||||
declare module 'react-18-input-autosize';
|
declare module 'react-18-input-autosize';
|
||||||
|
|
||||||
export { }
|
declare global {
|
||||||
|
// Google Analytics gtag types
|
||||||
|
type GtagEventParams = {
|
||||||
|
[key: string]: unknown
|
||||||
|
}
|
||||||
|
|
||||||
|
type Gtag = {
|
||||||
|
(command: 'config', targetId: string, config?: GtagEventParams): void
|
||||||
|
(command: 'event', eventName: string, eventParams?: GtagEventParams): void
|
||||||
|
(command: 'js', date: Date): void
|
||||||
|
(command: 'set', config: GtagEventParams): void
|
||||||
|
}
|
||||||
|
|
||||||
|
// eslint-disable-next-line ts/consistent-type-definitions -- interface required for declaration merging
|
||||||
|
interface Window {
|
||||||
|
gtag?: Gtag
|
||||||
|
dataLayer?: unknown[]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,14 @@
|
||||||
|
/**
|
||||||
|
* Send Google Analytics event
|
||||||
|
* @param eventName - event name
|
||||||
|
* @param eventParams - event params
|
||||||
|
*/
|
||||||
|
export const sendGAEvent = (
|
||||||
|
eventName: string,
|
||||||
|
eventParams?: GtagEventParams,
|
||||||
|
): void => {
|
||||||
|
if (typeof window === 'undefined' || typeof (window as any).gtag !== 'function') {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
(window as any).gtag('event', eventName, eventParams)
|
||||||
|
}
|
||||||
Loading…
Reference in New Issue