How can I add google analytics to my meteor app?

Hello guys,

I am using flowrouter, how can I add google analytics in a flowrouter trigger directly?
I mean, I want to avoid an additional plugin.

Thanks,

Please help, I guess this is very common for any.
Please help me anyone who has done this before.
Thanks a lot.

Hi @jpfernandezl, just as a question, why do you want to add the google analytics script only in one route?

1 Like

Hi,
I want to add it for all routes. How can I do that?

I would suggest that you use the req.dynamicHead property that WebApp uses to inject whatever html head content you like into the boilerplate html served for all routes.

Here’s some (Typescript) code copied from my app. I put all my favicons and other things, including the GA JS startup code into a single file in private/html/head.htm.

const loadHeadContents = (): string => {
  const result = Assets.getText("html/head.htm") ?? "";
  return result;
};

const headContents = loadHeadContents();

const headAppender: NextHandleFunction = function(req, res, next) {
  req.dynamicHead = headContents;
  next();
};

export const installWebappHooks = () => {
  // Copied from https://github.com/meteor/meteor/blob/devel/packages/browser-policy-common/browser-policy-common.js
  WebApp.rawConnectHandlers.use(headAppender);
};

and then I just call installWebappHooks from main.ts

HTH,
Per

Another option is to use the templating package which will inject head content from any .html file in your project - but it comes with a lot of dependencies (Blaze etc) that I was happy to get rid of when I found the req.dynamicHead property in the Meteor source code.