I’m having trouble making requests to the Google Drive API from my web app after authenticating with Google Identity. Every time I try to fetch data, I get hit with a CORS error that blocks my request.
The error message shows that the preflight request fails because there’s no Access-Control-Allow-Origin header in the response. I’ve already set up my authorized JavaScript origins in the Google Console to include my local development URL.
Here’s the function I’m using to get the files:
async function getFilesList(token) {
try {
const response = await fetch(
`https://www.googleapis.com/drive/v3/files?key=${encodeURIComponent(myApiKey)}&access_token=${encodeURIComponent(token)}`,
{
headers: {
'Authorization': `Bearer ${token}`,
'Accept': 'application/json'
},
method: 'GET'
}
);
console.log(response);
} catch (err) {
console.error(err);
}
}
I really want to keep this client-side since my use case doesn’t need server processing. Is there a way to make this work directly from the browser, or do I need to route everything through my backend server? Any tips on solving this CORS problem would be really helpful.
Had this same issue last month. You’re mixing authentication methods - passing both an API key and access token confuses Google’s servers and triggers CORS errors. Drop the API key from your URL. The Bearer token in your Authorization header is enough for authenticated requests. Also check that your OAuth 2.0 client ID was created for web applications, not other types. Google Drive API works client-side without CORS issues when set up right. Use the correct scope (https://www.googleapis.com/auth/drive.readonly for read access) during auth flow. This approach works reliably for my client-side apps.
cors issues can be tricky. just make sure your urls in google console match exactly with your dev setup, even the small details like http vs https. also, ya might wanna try removing the api key since you’re using a bearer token already. good luck!
This CORS issue comes from browser security when you’re hitting the API directly. Google Drive API does support CORS, but there’s a trick to it. Use the Google APIs JavaScript client library instead of raw fetch - it handles CORS and auth way better. The library deals with preflight requests and headers automatically. Make sure your domain in Google Console has the exact port number if you’re testing locally. CORS changes can take a few minutes to kick in after you update the console. If you’re stuck with fetch, initialize Google Identity Services first - it sets up the browser context you need for API calls.