In my blog post from earlier this week, I mentioned how Google has a new Analytics Embed API. While it still requires a bit of programming, it is a greatly simplified version of the code you needed before in order to work with Google Analytics. As you can guess, the primary use case (at least in my opinion) for this will be to embed charts on a web site so you don't have to go to the Google Analytics dashboard to see how well your site is doing.
Oddly though the docs don't show an actual example of that use case. Instead, all of the examples rely on your own particular Google Analytic site data and each demo asks you to select a property first. Now, I get that that makes it possible for us to actually see the demos. However, it doesn't give us an example of how you would embed this on a site and ensure that the report just shows that site's particular data. It's really relatively simple, but as I said, I was a bit surprised this wasn't demonstrated.
To see how you could do this, let's start with a demo that lets you pick a property, like the demos on the site. (And to be clear, this is a demo from their site, I didn't write it.)
<!DOCTYPE html>
<html>
<head>
<title>Embed API Demo</title>
</head>
<body>
<!-- Step 1: Create the containing elements. -->
<section id="auth-button"></section>
<section id="view-selector"></section>
<section id="timeline"></section>
<!-- Step 2: Load the library. -->
<script>
(function(w,d,s,g,js,fjs){
g=w.gapi||(w.gapi={});g.analytics={q:[],ready:function(cb){this.q.push(cb)}};
js=d.createElement(s);fjs=d.getElementsByTagName(s)[0];
js.src='https://apis.google.com/js/platform.js';
fjs.parentNode.insertBefore(js,fjs);js.onload=function(){g.load('analytics')};
}(window,document,'script'));
</script>
<script>
gapi.analytics.ready(function() {
// Step 3: Authorize the user.
var CLIENT_ID = '818125206534-g1r0datdtu9serq2pf9cp5vkuih3h8pv.apps.googleusercontent.com';
gapi.analytics.auth.authorize({
container: 'auth-button',
clientid: CLIENT_ID,
});
// Step 4: Create the view selector.
var viewSelector = new gapi.analytics.ViewSelector({
container: 'view-selector'
});
// Step 5: Create the timeline chart.
var timeline = new gapi.analytics.googleCharts.DataChart({
reportType: 'ga',
query: {
'dimensions': 'ga:date',
'metrics': 'ga:sessions',
'start-date': '30daysAgo',
'end-date': 'yesterday',
},
chart: {
type: 'LINE',
container: 'timeline'
}
});
// Step 6: Hook up the components to work together.
gapi.analytics.auth.on('success', function(response) {
viewSelector.execute();
});
viewSelector.on('change', function(ids) {
var newIds = {
query: {
ids: ids
}
}
timeline.set(newIds).execute();
});
});
</script>
</body>
</html>
That's nice, right? As I said, when I was building my own Google Analytics mashup it was quite a bit more complex than this. Here is a screen shot of the result - don't forget you can see this, and other examples, on the demo site for the API.

I've called out two things in the screen shot above. The first is the "You are logged in as" message. The Embed API does not let you remove this. You can change the text in front of the username, but even if you set the property to an empty string, the username will still show up. To me, this is useless information if I'm embedding in my site admin portal. And obviously the site picker itself is something we want to get rid of.
In order to make these changes, we just need to do a few things. Here's the updated code.
<!DOCTYPE html>
<html>
<head>
<title>Embed API Demo</title>
</head>
<body>
<!-- Step 1: Create the containing elements. -->
<section id="auth-button"></section>
<section id="timeline"></section>
<!-- Step 2: Load the library. -->
<script>
(function(w,d,s,g,js,fjs){
g=w.gapi||(w.gapi={});g.analytics={q:[],ready:function(cb){this.q.push(cb)}};
js=d.createElement(s);fjs=d.getElementsByTagName(s)[0];
js.src='https://apis.google.com/js/platform.js';
fjs.parentNode.insertBefore(js,fjs);js.onload=function(){g.load('analytics')};
}(window,document,'script'));
</script>
<script>
gapi.analytics.ready(function() {
// Step 3: Authorize the user.
var CLIENT_ID = '818125206534-g1r0datdtu9serq2pf9cp5vkuih3h8pv.apps.googleusercontent.com';
gapi.analytics.auth.authorize({
container: 'auth-button',
clientid: CLIENT_ID,
userInfoLabel:""
});
// Step 5: Create the timeline chart.
var timeline = new gapi.analytics.googleCharts.DataChart({
reportType: 'ga',
query: {
'dimensions': 'ga:date',
'metrics': 'ga:sessions',
'start-date': '30daysAgo',
'end-date': 'yesterday',
'ids': "ga:31405"
},
chart: {
type: 'LINE',
container: 'timeline'
}
});
gapi.analytics.auth.on('success', function(response) {
//hide the auth-button
document.querySelector("#auth-button").style.display='none';
timeline.execute();
});
});
</script>
</body>
</html>
So what did I change?
- I set userInfoLabel to an empty string in my authorize code. As I said, Google will still show the username in the div it is associated with, and we're going to fix that too, but this will at least make the text size smaller.
- In the DataChart embed, I hard code the ID for my property.
- Next, in my authentication success method, I hide the div that contains the authentication info.
And that's it. Here is the result - which would make more sense in an admin portal of some kind but I assume you can use your imagination:

By the way, you can customize the chart quite a bit as well. For example, here is a modification that adds a simple animation as the chart loads:
var timeline = new gapi.analytics.googleCharts.DataChart({
reportType: 'ga',
query: {
'dimensions': 'ga:date',
'metrics': 'ga:sessions',
'start-date': '30daysAgo',
'end-date': 'yesterday',
'ids': "ga:31405"
},
chart: {
type: 'LINE',
container: 'timeline',
options:{
'animation.duration':200,
animation:{
duration:1000,
startup:true
}
}
}
});
So, where did I get my ID value? Well for me, I simply modified the first code listing to console.log the ID value. Another way to get it would be to go your property settings, then to the View, and copy the View ID. Remember to add ga:
in front.
I hope this helps. To be clear, this will only work if the authenticated user has access to this particular ID. You may be wondering how to handle that. You could add an error handler to the auth code, but the user may authenticate just fine and not have access. Luckily you can also add an error handler to the timeline - as simple as this:
timeline.on('error', function(e) {
console.dir(e);
console.log('timeline err')
});
You wouldn't use the console to report the issue of course. You could easily add a message like, "Please contact Bob in IT so he can add you to the list of people who can access this GA account."
Archived Comments
Hi,
I have used this to display a table but the problem is I can't figure out how to format data. For instance I get time in seconds and I really dont know how to format it in minutes : seconds. Could you help me with that ?
Thanks in advance !
Can you show me what you have so far? Like online I mean.
Hi Raymond, thanks for this blowing fast answer.
This is the code that I use to generate the table :
var dataChart1 = new gapi.analytics.googleCharts.DataChart({
query: {
'ids': 'ga:xxxxxxx',
'start-date': '30daysAgo',
'end-date': 'yesterday',
'metrics': 'ga:sessions,ga:screenviews,ga:avgSessionDuration',
'dimensions': 'ga:appVersion'
},
chart: {
'container': 'chart-ios-container',
'type': 'TABLE',
'options': {
'width': '100%'
}
}
});
dataChart1.execute();
I sadly can't show you an online example as it is not accessible online but here is what the table looks like.
Thanks a lot !
So in your case, you are letting Google render the results, which is easy, but locks you down a bit in terms of how much you can customize. If you want more control, then you need to render everything yourself.
I don't want to promise, but I'm keeping this thread in my inbox to try to find time to make a demo for you.
http://www.raymondcamden.co...
I followed this tutorial and I get this, any chance you could help?
Expand the error so we can see it.
Hi,
I have to display the dashboard using tracking Id, because i have more than one websites to analyze. plese help.
I'm not sure I understand your question. You do see how I show multiple sites being available via the dropdowns, right? Their docs/demos show that too.
Hi Ray, thanks the tutorial. Quick question. I want to have the results show on a public web page, however you need to authorize the api to show them (This means only I can see them). How can I authorize the page so anyone can view the results?
For this - no. There is an API that can run entirely server side and you could use that instead.
Hi Ray, I've search the web but unfortunately I've had no luck in finding a step by step tutorial. Would you mind pointing me in the right direction please?
A step by step tutorial on how to use Google Analytics? Best I can say is to start here: https://developers.google.c...
Hi, this script does not work anymore you know what change do? Thank you
How does it not work? What do you see in your console?
All white
It worked for me. What do you mean by "All white" - you did open up the DevTools, right?
I do not understand how you can work! I just copied and pasted your code and I replaced CLIENT_ID. To me it does not work I only see a blank page
I keep asking you but you don't say: What do you see in the browser's developer tools console?
Excuse I have not written to you because you do not understand what you want me see in console development? The code is there but does not display the data. Tell me what you want me to do you see for console development?
Do you know what browser developer tools are?
Yes, you use Firebug.
Ok, when you use Firebug and look at the Console, do you see an error?
{"error":{"errors":[{"domain":"global","reason":"insufficientPermissions","message":"User does not have
sufficient permissions for this profile."}],"code":403,"message":"User does not have sufficient permissions
for this profile."}}
--------------------------------
"NetworkError: 403 Forbidden - https://content.googleapis...."
[object Object]
https://apis.google.com/_/s...
Line 596
If you used my later demo where I hard coded the profile id, then it won't work for you. I mention this here, "In the DataChart embed, I hard code the ID for my property.", but maybe I didn't warn you enough to change it.
So what should I change to make it work?
So what should I change to make it work?
I'm not talking about that. I'm talking about the *property* ID:
ids': "ga:31405"
That's my property. So your basically trying to read my GA data, which is why it works for me, not you.
Please read this again carefully as I told you already what to change.
See my comment. I've told you what to change a few times now.
ok thanks I try!
you know where I find my "ids"
See this part from the first demo?
timeline.set(newIds).execute();
If you console.log(newIds) you'll see the ID of the selected property.
maybe I'm stupid but I do not understand what to do, I put up your first example that works
You find that line I shared in the previous example. You paste in what I said above it. You reload the page and use the Firebug console and you will see it printed there.
ok I did it! Thanks you've been a great help! I have so many sites you know how to do and see just a website?
If you are asking - how do I show data for just one site - that's literally what this blog post here demonstrates.
Exact! But I having more than one site he shows me the first, I how do I tell him to show me the site number 5?
I'm not quite sure I understand. I think you want a Property, which is one site, and my code demonstrates how to do that.
So I do not understand, I always see the first property, how do I only see the second property? Thanks for your patience
You're kidding, right?
Forgive are not very practical, I'm not kidding, I'm trying, and I may not have your expertise.
You're last comment wasn't even English though.
or corrected
Remember when I said to add the console line so it would print the property id? If you still have that, and select the second property, it would show you the ID.
ok because that's what I did, or rather I could not understand, now I understand! Thanks again for your patience! ;o)
Hi Raymond,
the google auth_button is free stylable, though this is not allowed by google - see https://developers.google.c... . Google has a lot of policies, which handle their branding even a special button policy: https://developers.google.c... .
You can do it for example like that - it produces the button "Access Google Analytics" - as shown in the reply - added pic1.
</script>
<style>
.gapi-analytics-auth-styles-signinbutton-image { background-image:none !important; border-right:#ffffff solid 0px !important; width:0px !important; }
.gapi-analytics-auth-styles-signinbutton-buttonText {color: #6484A4; font-family:Arial !important; vertical-align:middle !important; line-height:11px !important; font-weight:normal !important; font-size:11px !important; width:130px !important; height:20px !important; padding-left:0px !important; padding-right:0px !important; }
.gapi-analytics-auth-styles-signinbutton{background-color: #D9DEE6 !important; border:#6484A4 solid 1px !important; width:130px !important; height:20px !important;}
.gapi-analytics-auth-styles-signinbutton:hover{background-color: #ffffff !important; border-bottom: #485871 solid 1px !important}
</style>
</head>
Best regards
Axel Arnold Bangert - Herzogenrath 2016
I didn't - maybe it was a misclick. I got a minor spam attack this morning.
I mean - I must have - but it wasn't on purpose.
No problem - you published fine articles
Best
Axel
pic1:
https://uploads.disquscdn.c...
If you want to see it online - it is here (I guess this will not be marked as spam :) )
http://gimba.de/Bangert%20A... . This page is not indexed by google and I shall change the button to its original style, for the above button style is illegal :) - I don't like color missmatches :)
Best
Axel
Hi Raymond,
this had been my question (before spam blocking): " ... do you perhaps know, how this Charts are to be made accessible for anonymous internet users? You told about a server side API that enables that "...There is an API that can run entirely server side ...". Is it this one https://ga-dev-tools.appspot.c... ? If it is this one I guess I have to install Google API Client Library for Python too? ..."
First I installed Google API Client Library for Python. And I got the json file. I guess now this step is the next one? Can I achieve with that server side authorization anonymous access to the g-analytics charts, embedded in my page?
# service-account.py
from oauth2client.service_account import ServiceAccountCredentials
# The scope for the OAuth2 request.
SCOPE = 'https://www.googleapis.com/...
# The location of the key file with the key data.
KEY_FILEPATH = 'path/to/json-key.json'
# Defines a method to get an access token from the ServiceAccount object.
def get_access_token():
return ServiceAccountCredentials.from_json_keyfile_name(
KEY_FILEPATH, SCOPE).get_access_token().access_token
Best
Axel
Hi Raymond, thank you for this article, very informative. I just need help with figuring out what the problem is in my web app that I'm trying to connect by using embed api. I passed the authentication process and I can see my account e-mail on the top, but there is no other info or any chart. I'm assuming only auth-button container works but view-selector and time-line is not. By the way, I used the exactly the same code in GA website and added my clientID. Here is the error shown in the console:
Object { error: Object } cb=gapi.loaded_0:604:203
uncaught exception: [object Object]
Appreciate your help to resolve this, thanks
Hi Raymond, Thank you for this article. I tried it and working fine. But what is happening is it is working when i logged only. I google analytics credentials just like client id. I want to display data in my website for all users. Can you help me to solve this problem?
See if you can click to expand the object. Basically [object Object] means theres a more complex object behind it - we need to see the details. If this is online, I can possibly help.
Not with *this* API. You would use the REST API to work with Google Analytics. You would need to Google for the docs for that - I don't have an example of that handy.
Hi Raymond, thanks for the prompt reply. I actually solved it by enable'in API from my google analytics account, suprisingly it was that simple because after all the set up, i should have just clicked the ENABLE button on my api console. Now i'll work on some styling by css and d3.js. Thanks again
Hi, Raymond. Thanks for the post.
Could you share your api credentials (Authorized JavaScript origins, and Authorized redirect URIs)?
I've been playing around with the analytics API for quite some time, and for some reason your clientID (818125206534-g1r0datdtu9ser...) works. However, I cannot get mine to populate data after authenticating. I simply get a blank screen. I assume that this is from an error in my api credential configuration. I'm running from a localhost via XAMPP. Thoughts?
You mean my settings, not my actual credentials, right?
Also - what do see in console?
Yeah, your settings.
To clarify: When I use your example clientID the program executes smoothly. However, when I use my generated one, I can authenticate and then I receive a blank screen.
Console reads: Failed to load resource: the server responded with a status of 403 ()
cb=gapi.loaded_0:604 Object_.nH @ cb=gapi.loaded_0:604
Which one are you using? If you are using the one with the hard coded IDs then it shouldn't work for you:
'ids': "ga:31405"
First off, thank you so much for the prompt replies and willingness to help.
I'm using the original example, which I believe does not use hardcoded ids.
viewSelector.on('change', function(ids) {
var newIds = {
query: {
ids: ids
Is this online where I can see?
No, I'm running a local server with XAMPP. Is there anything specific that you would like to see? I'd be happy to provide screenshots.
I believe the problem stems from my api credentials not being configured correctly. I say this because the code executes perfectly for the example clientID.
CLIENT_ID = '818125206534-g1r0datdtu9ser...'
However, when I use my clientID -- which I have set up through the Google API console, I receive a blank screen and the console error that I noted above.
I'm looking at my project now. I have analytics enabled for my project. I have an OAuth 2.0 client ID created. Ca n you verify you have done that too?
You're a lifesaver! I had my OAuth 2.0 established like a week ago. However, I did not know that I needed to enable analytics within the project as a whole. This is my first attempt at Google API development. Sincerely appreciate it!
No worries. When you make millions with this, visit the wishlist and get me an XBox One. ;)
You have my word: if I make a million, you'll get an xbone. Take care.
hi, I have the same issue. Did you find any solution?
You can't do that with the embed API. They have a REST-based API you could use. You would need server-side software to do it.
hi, how to get my client id ??
thanks
If you mean the main client id, you get that when you add the API in the Google portal. If you mean for a particular site, I explain how in the blog post.
Hi, Raymond. Thanks for the post.
I want to show GA data from other website on my website ,is that possible? , If yes what keys or things i need ?
Hope i would get my answer ..
Thanks,
Diwakar
The Embed API allows you to access sites that you have access to. So if you have access to those other sites, it should just work.
Thank you so much for your prompt reply,
In above sample code i don't know where i can link it to target website or how it can be done.
I will be great full if you can link some example .
Thanks Again..
I don't understand what you are asking. The Embed API works with the sites that you have access to. It's basically using your account so its automatically going to select your sites.
Hi Raymond... Im beginner in GA. I tried to embed GA into my website dashboard , its work already but something error in my Pie chart. I need to show 3 reports (Visit, Product Page, Services Page) but Product and Services data become 1 on 1 pie chart.. Your post is very helpful
Glad it was helpful. :)
But theres still a problem to separate 2 data's in 1 chart, and i really dont know whats wrong with my code, i already check and searching on developers.google.com/analy..., but i still dont get the solution. May you help me??? where i can send the code?
Ah sorry - I haven't used this in a while. This kind of help would need to be a paid engagement. I hope you understand.
Hi..It's works. Any method for show only one time authorization user button in dashboard?
Thanks in advance :)
The Auth is handled by Google, so they would decide how long to persist it. In my testing, it seemed to last quite a while, but I use my various Google services all day.
Found the Solution. Thanks :)
https://uploads.disquscdn.c... Hi, i am facing an issue, As I'm new to coding, i couldn't find out the issue. When i try the example above, i see a blank page with this message in the console
"Uncaught >Object {error: "idpiframe_initialization_failed", details: "Not a valid origin for the client."}"
Google makes you set up IP addresses that are valid to use the API with your keys. You'll need to handle that on the Google side.
Please share solution. Thanks.
is it at all possible to test on a local host?
hi Ray, https://uploads.disquscdn.c...
i used your sample code and all i get is a blank screen. and the error i get is below.
Yep.
Are you testing from a file:// url or localhost?
right now im just testing from a file
Don't. Ever. So many things don't work right. If you don't have a local web server, look at httpster as a quick and easy Node based web server.
you are amazing "THANK YOU!!!!!"
i spent countless hours trying to figure it out
It's ok - I'm going to blog on this tomorrow as a reminder.
you are amazing person and much Brilliant "THANK YOU SO MUCH REALLY THANKU!!!!!"
i spent MUCH hours.......... U R TOOO GREAT
Glad you found it helpful!
Store authorization value in php.
To be clear, imo, this is a mistake. If you want to do that, I'd use the regular REST API for GA versus this one, which is specifically meant for client-side apps only.
Thank you. I have a little bit knowledge so just try to play with code and found the solution as per my requirement. Your solution such a helpful for me.Thanks alot again for informed way of solution.
Hi Ray,
I am new to Google analytics and trying to embed the GA reports on website.
Your blog is very usefull and I followed the steps given by you . I am facing an issue . I am running html on local webserver and getting the below error. I am using correct ID and the proper Client ID as well . please help. https://uploads.disquscdn.c...
You have to enable localhost in the Google Dashboard for this API.
Thanks you Ray for quick reply, Now its working fine.
Hi Ray,
I am able to embed GA in web app, your blog is very useful. Thanks for sharing the information.
I need to perform OAuth so that without logging into GA ,the data can be accessed. Now without logging into Google analytics its not possible to embed the GA report in web app. Please help me how to perform Oauth in web app using Embed API.
Google has a REST based API and you could use it to perform authentication behind the scenes, but you couldn't do this for OTHER users w/o them logging in _some_ way. If it was for your own properties, then you could. Also, all the "auto visuals" and stuff would have to be built by hand. You could get the same results, but it's going to be manual work.
I honestly don't remember if I've blogged on it. Best I can suggest is Google's documentation.
How to enable the localhost from dashbord , i didnt find that option..some help plz
You should be able to add it as a referrer.
sory didnt understand you , can you plz , explain more
When you go to the Google Console to add support for the API, it should also have a place where you define the referrers. Ie, who can use your API (or where to be more precise). Look at the docs here: https://developers.google.c...
Hi Raymond,
I am not able to get GA dashboard through this upper given java script.
you have mentioned two thing client id and GA id but i already have these two things.
Please help me out on this.
Thanks in advance,
Harshit garg
What error do you see in your browser console?
Acutely I am not getting any error but when i have passed client id and ga id but when i am running that code it is not giving any output.
Please help me out on this..it is urgent
To be clear, I do not provide urgent support for free, especially on the weekends. If you want critical support, you can contact me directly about a paid engagement.
Now - with that being said, what do you see in the console? Are you sure you saw nothing in devtools?
i am just getting message : "You are logged in as: ***********@gmail.com"..
NO charts are showing
Ok - the You are logged in thing is *expected* - no charts though could be a bug. What do you see in DevTools?
I'm coding an admin panel dashboard on my website and when I clear my cache I'm presented with 'access google analytics' and have to login to my google account again. Can I make it so it auto authenticates any administrator accounts on the site so they don't have to login to google at all?
If by 'cache' you also meant cookies, then I'd say not. Google has a REST based API for GA that you could use instead. It isn't as simple of course.
What line is that and can I see it online myself?
When execute above code this errors comes : uncaught exception: [object Object]
Please help me out on this.
Check the console for the full error. It should give you more details then that.
How will the 'chart' part look like if you are using the Analytics Reporting API v4?
I don't know - haven't tried yet. :)
i took your code and made one change(i set client id) but when i am run this code it does't show any things? what should i do?
What does the browser console show?
+1
As I said to Chris, check your console for the full error. If this is online, share the URL and I can take a look.
thank you very much!
If anyone gets an error, FYI the message will most likely contain a-lot of information about whats wrong
'dimensions': 'ga:date',
What should we put in the dimensions if we want to see the timeline "per month", instead of "per day" ?
It's been a few years since I've worked on this, so the best I can suggest is what I'd do - check the docs. :) Please comment back if you find it.
yes, after your reply it was easy to find it.
The parameter is ga:yearMonth
The list of other dimensions is at: https://developers.google.c...
My idea is to build a set of pre-configured GA reports to be used for the reporting of usage statistics of the SoftMeter library ( https://www.starmessagesoft... )
Cool glad you got it! :)
If I don't login the first time I navigate to this page and then move to some other page and navigate back to this page, none of the containers are visible in this page
I guess try reloading then? This was just a simple demo and the assumption was that you wouldn't do stuff like that. :)
how to make google signin session for multiple page
am getting this error
cb=gapi.loaded_0:117 Uncaught TypeError: Cannot read property 'style' of null
You would need to use the embed twice I suppose.
Hello,
Is it possible to add the code in iframe?
If possible , how to do so?
Thank you,
Siddarth S
Did you try it in an iframe? Let me know what you see.