API Realtime Google Analytics Is Not Working On Client Side With Js

enter image description here

I have tried use API key, and OAuth 2.0.

As result I have this error:

Which API key should I use? What mistakes have I made?


    function start() {
        // 2. Initialize the JavaScript client library.
            'apiKey': 'XXXXXX',
            // clientId and scope are optional if auth is not required.

        }).then(function() {

            return gapi.client.request({
                'path': '',
        }).then(function(response) {
        }, function(reason) {

            console.log('Error: ' + reason.result.error.message);
    gapi.load('client', start);



First you need to understand the diffrence between private and public data. Public data is data that is not owned by anyone. Anyone can search for YouTube videos in the Youtube api for example

Google analytics data on the other hand is private it is owned by a user. Api keys are used to access public data not private data. In order to access private google analytics data you will need to be logged in as a user who has access to that data.

The tutorial quickstart js Will show you how to access google anlaytics data using JS you will have to alter it for the realtime api i am not a js developer so cant help with that but you should be able to understand the login process using this sample

<!DOCTYPE html>
  <meta charset="utf-8">
  <title>Hello Analytics Reporting API V4</title>
  <meta name="google-signin-client_id" content="<REPLACE_WITH_CLIENT_ID>">
  <meta name="google-signin-scope" content="">

<h1>Hello Analytics Reporting API V4</h1>

<!-- The Sign-in button. This will run `queryReports()` on success. -->
<p class="g-signin2" data-onsuccess="queryReports"></p>

<!-- The API response will be printed here. -->
<textarea cols="80" rows="20" id="query-output"></textarea>

  // Replace with your view ID.

  // Query the API and print the results to the page.
  function queryReports() {
      path: '/v4/reports:batchGet',
      root: '',
      method: 'POST',
      body: {
        reportRequests: [
            viewId: VIEW_ID,
            dateRanges: [
                startDate: '7daysAgo',
                endDate: 'today'
            metrics: [
                expression: 'ga:sessions'
    }).then(displayResults, console.error.bind(console));

  function displayResults(response) {
    var formattedJson = JSON.stringify(response.result, null, 2);
    document.getElementById('query-output').value = formattedJson;

<!-- Load the JavaScript API client and Sign-in library. -->
<script src=""></script>