Issue with JavaScript accessing Google Drive API files

I am building a web app that needs to list files from Google Drive using JavaScript. However, I am encountering an error related to the files endpoint and I’m not sure why.

Here is how I’ve implemented my code:

var clientId = '*********.apps.googleusercontent.com';
var apiKey = '##########';
var scopes = 'https://www.googleapis.com/auth/drive';

function loadClient() {
    gapi.client.setApiKey(apiKey);
    window.setTimeout(checkAuthorization, 1);
}

function checkAuthorization() {
    gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: true}, handleAuthorization);
}

function handleAuthorization(authResult) {
    var loginBtn = document.getElementById('login-button');

    if (authResult && !authResult.error) {
        loginBtn.style.visibility = 'hidden';
        makeApiCall();
    } else {
        loginBtn.style.visibility = '';
        loginBtn.onclick = requestAuth;
    }
}

function requestAuth(event) {
    gapi.auth.authorize({client_id: clientId, scope: [scopes], immediate: false}, handleAuthorization);
    return false;
}

function makeApiCall() {
    gapi.client.load('drive', 'v2', executeApiCall);
}

function executeApiCall() {
    var apiRequest = gapi.client.drive.files.list({'maxResults': 5});

    apiRequest.execute(function(response) {
        for (var i = 0; i < response.items.length; i++) {
            var filename = response.items[i].title;
            var lastModified = response.items[i].modifiedDate;
            var modifiedBy = response.items[i].lastModifyingUserName;
            var embedLink = response.items[i].embedLink;
            var alternateLink = response.items[i].alternateLink;

            var listItem = document.createElement('li');
            listItem.appendChild(document.createTextNode('NAME: ' + filename + ' - LAST MODIFIED: ' + lastModified + ' - MODIFIED BY: ' + modifiedBy));
            document.getElementById('file-content').appendChild(listItem);
        }
    });
}

The error I’m facing is:

Uncaught TypeError: Cannot read property 'files' of undefined

This occurs specifically at the line:

var apiRequest = gapi.client.drive.files.list({'maxResults': 5});

What might be the issue? The authentication seems to work fine but the API call does not.

looks like your executeApiCall might be firing too soon. try adding a check to see if gapi.client.drive is ready before making that request, or use some error handling to catch it.

You’re using the old Drive API v2 with legacy gapi.auth methods - that’s your problem. Google deprecated those endpoints and they’re unreliable now. Switch to Drive API v3 and update your auth flow. Change gapi.client.load('drive', 'v2', executeApiCall) to gapi.client.load('drive', 'v3', executeApiCall) and update your executeApiCall function. I’d also recommend ditching gapi.auth for Google Identity Services library. Had the same issue last year on an old project - migrating to v3 fixed all the undefined client errors.

This is a timing issue with your API loading. gapi.client.load returns immediately, but the actual loading happens in the background. Your executeApiCall function runs before the Drive API finishes loading, so you get undefined errors. The third parameter in gapi.client.load('drive', 'v2', executeApiCall) is supposed to be a callback, but there’s still a race condition. I hit this exact problem building a document management system. Fixed it by adding proper callbacks and checking if the client exists before making calls. Make sure the API loads completely before trying to access gapi.client.drive.files. Add a check like if (gapi.client.drive && gapi.client.drive.files) before your request.