Add Simple Analytics to a GatsbyJS website
2 min read
399 words
I want to use analytics on my page for a long time. But using Google Analytics was a no go for me because of its’ privacy issues. So I looked out for privacy focused analytics software very early. Especially cookie-less analytics were something is something that I want to use. I don't like those cookie banners, so having a solution without one would be a great thing. Simple Analytics and Fathom Analytics were solutions I liked. Both are bootstrapped indie companies which is something I value very much.
Simple Analytics is available in the GitHub education pack. It is possible to use it as a student for free for 1 year. So today was the day where I blocked the time to implement it on my GatbsyJS blog. In the following I will talk about how easy it is to add it to a GatsbyJS page.
Installation
First you have to create an account with Simple Analytics. When you already have an account log into it. When you don't have a website added yet you will be redirected to the page where you can add one. Otherwise go to your dashboard and click on the Add website button. Then create add your website’s URL and hit the Add website button below the form.
To now add the script
tags that are required to make the analytics work at the
end of your body
tag open up the gatsby-ssr.js
file or create it in your
Gatsby root directory. Inside of the file add the following lines:
export const onRenderBody = ({ setPostBodyComponents }) => {
setPostBodyComponents([
<script
async
defer
src="https://scripts.simpleanalyticscdn.com/latest.js"
/>,
<noscript>
<img src="https://queue.simpleanalyticscdn.com/noscript.gif" alt="" />
</noscript>,
]);
};
setPostBodyComponents
will add the content of the array at the end of the
body
in the html.js
file created by GatsbyJS.
After that you can check if your page is able to build. If successful you can push your page to production. After finishing the GatsbyJS build and pushing it to the web, Simple Analytics will find your page automatically and will present you your website's dashboard. That's it. You successfully added Simple Analytics to your GatsbyJS site.
Thank you for reading,
Niklas