Consent Management
Background
Many third-party scripts include tracking cookies that require user consent under privacy laws. Nuxt Scripts simplifies this process with the useScriptTriggerConsent composable, allowing scripts to be loaded only after receiving user consent.
Usage
The useScriptTriggerConsent composable offers flexible interaction options suitable for various scenarios.
See the API docs for full details on the available options.
Accepting as a Function
The easiest way to make use of useScriptTriggerConsent
is by invoking the accept
method when user consent is granted.
For an example of how you might lay out your code to handle this, see the following:
export const agreedToCookiesScriptConsent = useScriptTriggerConsent()
Accepting as a resolvable boolean
Alternatively, you can pass a reactive reference to the consent state to the useScriptTriggerConsent
composable. This will automatically load the script when the consent state is true
.
const agreedToCookies = ref(false)
useScript('https://www.google-analytics.com/analytics.js', {
trigger: useScriptTriggerConsent({
consent: agreedToCookies
})
})
Delaying script load after consent
There may be instances where you want to trigger the script load after a certain event, only if the user has consented.
For this you can use the postConsentTrigger
, which shares the same API as trigger
from the useScript
composable.
const agreedToCookies = ref(false)
useScript('https://www.google-analytics.com/analytics.js', {
trigger: useScriptTriggerConsent({
consent: agreedToCookies,
// load 3 seconds after consent is granted
postConsentTrigger: new Promise<void>(resolve => setTimeout(resolve, 3000))
})
})