Search code examples
node.jsgoogle-analyticsgoogle-analytics-apigoogle-analytics-data-api

How to query Google Analytics without viewId


Seems like Universal Analytics is deprecated and new version of Google analytics doesnt provide a viewId?

Does anyone know how to get google analytics data without having a viewId?

  googleAuth.authenticate(authOptions, function (err, token) {
        axios.get(`https://www.googleapis.com/analytics/v3/data/ga?ids=ga%3A219265842&start-date=${startDate}&end-date=today&metrics=ga%3Ausers&dimensions=ga%3Acountry&access_token=${token}`)
            .then(analyticsData => {
              
                // res.json(analyticsData)
            })
            .catch(err => console.log(err))
    });

This code was working up until few weeks ago with existing google analytics accounts with viewId.

https://support.google.com/analytics/answer/2790010?hl=en

"Universal Analytics refers to the previous generation of Analytics. This was the default property type for websites prior to October 14, 2020."


Solution

  • For anyone having the same issue:

    googleAuth.authenticate(authOptions, function (err, token) {
            var data = {
                "entity": {
                    "propertyId": "YOUR_PROPERTY_ID"
                },
                "dateRanges": [
                    {
                        "startDate": startDate,
                        "endDate": "today"
                    }
                ],
                "dimensions": [
                    {
                        "name": "deviceCategory"
                    }
                ],
                "metrics": [
                    {
                        "name": "totalUsers"
                    }
                ]
            };
    
            var config = {
                method: 'post',
                url: `https://analyticsdata.googleapis.com/v1alpha:runReport?key=${keys.GOOGLE_API_KEY}`,
                headers: {
                    'Authorization': `Bearer ${token}`,
                    'Content-Type': 'text/plain'
                },
                data: data
            };
    
            axios(config)
    .then(res=>{
    console.log(res)
    })
    .catch(err=>console.log(err))
    
    })