0%

How to add Google Analytics in Hexo with Next theme

Make sure your Hexo and Next theme are up to date.

Step 1:

open the {HEXO_ROOT}\themes\next\_config.yml file and find the following code:

1
2
custom_file_path:
#head: source/_data/head.swig

remove the # from the “#head: source/_data/head.swig” line.

Step 2:

create a file {HEXO_ROOT}\source\_data\head.swig and put the GA code in this file:

1
2
3
4
5
6
7
8
9
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());

gtag('config', 'G-XXXXXXXXXX');
</script>

Step 3:

rebuild your site

1
2
3
hexo clean
hexo g
hexo s