Adding Google Analytics to Ghost

In the early days of Ghost, you'd need to change your theme files to add the Google Analytics code snippet. With the introduction of Code Injection in the 0.6.0 release, you can now add the snippet in your admin panel.

We will walk you through each method, and weighs up the pro's and con's of each. But first, go to Google Analytics and create a new property for your blog, and obtain a Tracking ID.

Copy the code snippet under Website tracking.

Code Injection

Go to the Code Injection page in your blog's admin panel (<your-domain>/ghost/settings/code-injection/) and paste in the code snippet into the Blog Header textarea.

Press Save and you're golden!

Adding to Theme

Open up the default.hbs file in your theme's directory. Paste your code under {{ghost_head}} but before the closing </head> tag.

        (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),

        ga('create', '<tracking-code>', 'auto');
        ga('send', 'pageview');

Restart Ghost by shutting it down using Ctrl+C and then npm start --production, or if you're running Ghost with PM2, you can restart without any downtime by running pm2 reload <name-of-your-process>.

Considerations for Code Injection for Google Analytics

Here are some reasons why adding the Google Analytics code snippet to you theme is a better approach.

  1. Your theme must support Code Injection by adding {{ghost_head}} and {{ghost_foot}} helpers into the templates. This is not much of a problem since the most popular themes do.

  2. Your code is stored inside the SQLite database (in the settings table under the key ghost_head and ghost_foot. Because our content is not tracked in Git, this means the code snippet is not version-controlled.

  3. The Google Analytics code snippet would probably never change, by having it editable from the admin panel increases the chance of it being edited incorrectly or malformed, possibly through a typo.

  4. Having Code Injection enabled is a security risk. If someone access your admin panel, or hack into your database, they can inject malicious code into your visitors' browsers.

    This has been the practice of many CMS systems (mostly looking at the PHP camp), and it's one that needs to go away.

The only time code injection is useful is during development phase, when you want to test a script or library quickly without having to change and/or commit the code.


I'd very much recommend the second approach - adding the code directly into your theme.

While in production, I'd also recommend commenting out the {{ghost_head}} and {{ghost_foot}} helpers to prevent code injection, just in case someone looked over your shoulder and steals your password.

Daniel Li

Full-stack Web Developer in Hong Kong. Founder of Brew.

Hong Kong