nuxtjs/google-tag-manager only add google analytics when cookie consent has been given - vue.js

I'm currently trying to make my Tracking Opt-In. Meaning that before Google Analytics tracks the user, the user has to give consent. My website uses Nuxtjs and the #nuxtjs/google-tag-manager. In the nuxt-config.js I set it up like this modules: [
'nuxt-leaflet',
'#nuxtjs/redirect-module',
['#nuxtjs/moment', { locales: ['de'], plugin: false }],
['#nuxtjs/sitemap', {
path: '/sitemap.xml',
generate: false,
cacheTime: (1000 * 60 * 60), // generate every hour
gzip: true,
hostname: 'https://kreuzwerker.de',
routes () {
return generateSitemap()
}
}],
['#nuxtjs/google-tag-manager',
{
id: '/*GTM-Code*/',
dev: true // to disable in dev mode
}]
],
and it works perfectly fine but now I want to connect it somehow to my Cookie Consent Form. How would I do that?

First of all, you're using a deprecated nuxtjs module; use the new GTM module, right here; https://github.com/nuxt-community/gtm-module.
In your config, make sure you've set the following:
gtm: {
autoInit: false
}
Once you've gotten consent, in your form, call a callback function which calls the GTM init function; $gtm.init('GTM-XXXXXXX').
Good luck, read the GitHub page it explains it all.

Related

Office Word add-in – Msal using login redirect not working on Mac (Safari webkit 1.0)

We’re using Azure B2C to authenticate the users in the Word add-in. The library in Angular (14.1.2) that we use is MSAL which works as expected on Windows.
However, when using it on Mac, the redirect inside the add-in dialog gets stuck and doesn’t go to the Azure B2C page. It writes the cookies and local storage, but never redirects.
angular 14.1.2
azure/msal-angular 2.5.1
azure/msal-browser 2.32.1
Call
this.msalService.loginRedirect().subscribe();
Msal Configuration
`export function msalInstanceFactory(appConfigService: AppConfigService): IPublicClientApplication {
const appConfig = appConfigService.config;
return new PublicClientApplication({
auth: {
clientId: appConfig.aadB2CClientId,
authority: 'https://${appConfig.aadB2CDomain}/${appConfig.aadB2CTenant}/${appConfig.aadB2CSIPolicy}',
redirectUri: appConfig.aadB2CRedirectUri,
postLogoutRedirectUri: getLocationOriginWithPath('logout'),
knownAuthorities: [appConfig.aadB2CDomain],
navigateToLoginRequestUrl: false,
},
cache: {
cacheLocation: BrowserCacheLocation.LocalStorage,
storeAuthStateInCookie: isIE,
},
system: {
loggerOptions: {
loggerCallback: msalLoggerCallback,
logLevel: LogLevel.Verbose,
piiLoggingEnabled: true,
},
},
});
}
export function msalGuardConfigFactory(appConfigService: AppConfigService): MsalGuardConfiguration {
return {
interactionType: InteractionType.Redirect,
authRequest: {
scopes: appConfigService.config.aadB2CConsentScopes,
loginHint: getLoginHint(),
},
};
}`
The funny fact is that if I set a break point just before the execution of the loginRedirect and then press continue it works. So, I tried to set a timeout before that to see if it works but it doesn't.
Also tried to disable ITP security in Safari, but didn't take any effect.

Nuxt auth with keycloak: ssr this.$auth.loggedIn always false on page load

I have a setup with nuxt and keycloak as auth strategy which in general is working. I can login via keycloak and then will have this.$auth.loggedIn === true on the page. When navigating via vue-router, this.$auth.loggedIn will also be true when switching to a new page.
But when I then reload the page (CMD+r/F5), server side rendering will have false for this.$auth.loggedIn, while on client side it will be true. This forced me to do a lot of <client-only> blocks in the templates to prevent ssr mismatches.
I wonder if it is possible that on first page load server side rendering can return a page with authorized content? I would think this should be possible since cookies with auth info are set and sent to the server.
Or is that never possible and efficient server side rendering can only be used for non-authorized content?
Versions:
nuxt: 2.15.8
#nuxtjs/auth-next: 5.0.0-1643791578.532b3d6
nuxt.config.js:
auth: {
strategies: {
keycloak: {
scheme: 'oauth2',
endpoints: {
authorization: `${ process.env.KEYCLOAK }/protocol/openid-connect/auth`,
userInfo: `${ process.env.KEYCLOAK }/protocol/openid-connect/userinfo`,
token: `${ process.env.KEYCLOAK }/protocol/openid-connect/token`,
logout: `${ process.env.KEYCLOAK }/protocol/openid-connect/logout`,
},
token: {
property: 'access_token',
type: 'Bearer',
maxAge: 1800,
},
refreshToken: {
property: 'refresh_token',
maxAge: 60 * 60 * 24 * 30,
},
responseType: 'code',
grantType: 'authorization_code',
clientId: process.env.CLIENT_ID,
scope: ['openid', 'profile', 'email', 'roles'],
codeChallengeMethod: 'S256',
redirect: {
logout: '/',
callback: '/',
home: '/',
},
},
},
},
Having a Vue component with this:
created() {
console.log(this.$auth.loggedIn);
},
Will return false for SSR and true on client side on page load/refresh when logged in.
After manually implementing a server side authenticator, I found out that the problem was my local docker setup.
Didn't think this was the problem before, so I forgot to mention it.
I have a local docker container with keycloak and a local docker container with nuxt.
Long story short, it seems that the nuxt server wasn't able to communicate with keycloak, hence wasn't able to fetch the user. After changing some addresses so that keycloak was available on the same address from the browser and from within my nuxt server docker container, the nuxt server did get $auth.loggedIn=true automatically on page load if the is was logged in.
Not sure if I didn't see it, but I wished nuxt auth would give me an error if the nuxt server failed to communicate with the authorization server. Would have saved me a lot of debugging.

How does Nuxt.js auth use refresh tokens?

I have a Nuxt.js app with Nuxt auth module for authentication. My backend is in Phoenix with Pow used to handle authentication. When I log in I get 2 tokens from my backend: access token and a refresh token. I understand that access tokens are meant to be short-lived while refresh tokens last longer and are used to extend a session. My Nuxt app has the following settings inside nuxt.config.js to read the 2 tokens:
auth: {
...
strategies: {
local: {
token: {
property: 'data.access_token',
maxAge: 1800,
type: '',
},
refreshToken: {
property: 'data.renewal_token',
maxAge: 60 * 60 * 24 * 30,
type: '',
},
...
},
},
I also have this middleware:
router: {
middleware: ['auth'],
},
So far I've only been able to test and verify that my frontend is successfully able to make use of the access token but I've got no idea whether it is using the refresh token and if so, then how. I'd really appreciate it if someone would be able to explain (1) how Nuxt auth uses the refresh tokens, (2) if I'm missing anything in my setup and (3) if there is any way to specifically test the refresh token usage.
Many thanks!

How to change BaseStore from SAP Spartacus storefront

As Spartacus is for B2C process there is no any option to change BaseStore from storefront. I have a drop down for different countries and now want to change BaseSite from it.
So finally I made it working. I am storing baseSite to session if its changed from dropdown and if user is coming back reading it first from session.
here what you have to do to make it working:
Override BaseSite service and change initialize method similar to the initialize method of LanguageService. (which check if baseStore is stored in session )
Listen to SET_ACTIVE_BASE_SITE action and set payload to session. (again similar like activeLanguage effect in LanguagesEffects)
Now in B2cStorefrontModule config add your other sites as
B2cStorefrontModule.withConfig({
context: {
baseSite: ['electronics','mystore2','mystore-uk', 'mystore-canada'],
language: ['en'],
currency: ['USD']
}
So the main solution is, you listen to basestore change action and store the value to session and on page load you read basestore from session
I think you are looking for this. Check full code on Building the Spartacus Storefront from Libraries
B2cStorefrontModule.withConfig({
backend: {
occ: {
baseUrl: 'https://localhost:9002',
prefix: '/rest/v2/',
legacy: false
}
},
authentication: {
client_id: 'mobile_android',
client_secret: 'secret'
},
context: {
baseSite: ['electronics']
},
i18n: {
resources: translations,
chunks: translationChunksConfig,
fallbackLang: 'en'
}
}),

How to add Matomo tracking code in VueJS Single Page Apps?

I wanted to confirm whether I got my analytics tracking setup correctly in my single page application within the VueJS framework.
I am using the Vue plugin for Matomo which is found here:
https://github.com/AmazingDreams/vue-matomo
I imported the VueMatomo plugin in my main.js entry file like so:
import VueMatomo from 'vue-matomo';
Then, I assign the VueMatomo as a global method in my main.js file like so:
Vue.use(VueMatomo, {
// Configure your matomo server and site
host: 'https://matomo.example.com', <-- i configured this to match my real site
siteId: 5, <--- i configured this to match my real site
// Enables automatically registering pageviews on the router
router: router,
// Enables link tracking on regular links. Note that this won't
// work for routing links (ie. internal Vue router links)
// Default: true
enableLinkTracking: true,
// Require consent before sending tracking information to matomo
// Default: false
requireConsent: false,
// Whether to track the initial page view
// Default: true
trackInitialView: true,
// Changes the default .js and .php endpoint's filename
// Default: 'piwik'
trackerFileName: 'piwik',
// Whether or not to log debug information
// Default: false
debug: false
});
That gives me access to the Matomo API (_paq) in my components. However, this is where I am confused.
For example, I have a view called overview.vue which is the main page of the site. In this vue template, I have the following code in my created() hook. Since I am using a SPA, I need to somehow get the name of the page that the user is on and push it to the Matomo Reporting Tool. This is what I did:
<template>...snip...</template>
<script>
export default {
name: 'OverView',
created: function() {
window._paq.push(['setCustomUrl', '/' + window.location.hash.substr(1)]);
window._paq.push(['setDocumentTitle', 'Overview Page']);
window._paq.push(['trackPageView']);
}
};
</script>
Is the above adequate or is there a better lifecyle hook (mounted?) for the tracking code? Perhaps navigation guards are more appropriate?
Thank you
I got matomo working on my vue.js app (v 2.6.10).
I'm using a trial account from https://matomo.org/
In my main.js file:
// Analytics
import VueMatomo from "vue-matomo";
Vue.use(VueMatomo, {
host: "https://example.matomo.cloud", // switch this to your account
siteId: 1, // switch this as well you can find the site id after adding the website to the dashboard.
router: router,
enableLinkTracking: true,
requireConsent: false,
trackInitialView: true,
trackerFileName: "piwik",
debug: true
});
I can confirm that all of my nested routes are tracked. I can see what pages i viewed on my matomo dashboard.
To get custom events working just add the following:
this.$matomo.trackEvent("Event Category", "Event Name", "event action");
To give this some context, for my app i'm using it in a computed property:
computed: {
selectedMapDataType: {
get() {
return this.$store.state.mapDataType;
},
set(selected) {
this.$matomo.trackEvent("Dashboard Update", "Dashboard Data", selected);
this.$store.dispatch("updateMapDataType", selected);
}
},
...}