Page views over a given range.
Get Access To Analytics
To gain access to the Google Analytics API, you need to:
- Go to the Google Developer Console.
- Create a new project.
- Credentials -> Create Credentials -> Service-account key.
- Click “Enable APIs and services.”
- Find "Google Analytics API" and enable it.
Create Service Account
Since we're communicating server-to-server, we'll need a service account.
- Go to your service accounts page.
- Create a service account.
- Click "Create Key" and choose JSON.
You should now have a JSON file similar to this:
- On the table row, click Actions -> Edit.
- Show Domain-Wide Delegation -> Enable G-Suite Domain-Wide Delegation.
Finally, we need to add our service account email to the Google Analytics account we want to use.
- Go to the Admin panel inside Google Analytics.
- Click "User Management."
- Add the
client_emailfrom your service account.
Add Environment Variables
To securely access the API, we need to include the secret with each request. We also do not want to commit secrets to git. Thus, we should use an environment variable. Learn how to add environment variables in Vercel.