Let's assume you have Google Analytics setup for your account and you want to display your analytics in your application like this. Well Google has an API you can use.
You can call this API from a Next API as follows:
1
Create a Google Service Account
- Go to Google Developer Console and create a new project if you haven't already.
- On the sidebar click on Credentials and then Create Credentials
- Select Service Account as the credential type.
- Go back to the Credentials page and select Service Accounts
- Select Keys tab and then Add Key then create a JSON key
- Download and keep this JSON key safe.
2
Enable the Google Analytics Data API
- On the sidebar click on APIs & Services and ENABLE APIS AND SERVICES
- Search for Google Analytics Data API and enable it
- Go to Analytics dashboard and click on Admin -> Property User Management -> Add Users
- Add your service account email address (look in the JSON key for the email) and give it Read and Analyze access.
This may be a little confusing but you are just granting the service account you just created access to the Google Analytics Data API so you can use it in your Next app.
3
Install the @google-analytics/data package
npm install @google-analytics/data
oryarn add @google-analytics/data
- Set the client_email, client_id and private_key as env variables in your .env.local file
4
Get the Data (create a Next API)
5
Show the Data
Here's the exact React component I used as linked above. The markup is styled using Tailwindcss so that may look unfamiliar, but we just call the Next API using useSWR (which calls the Google Analytics API) and then we show Page Views, Engagement and Users.