This project is a React and TypeScript application built with Vite, integrating with the Google Drive API to read and write files.
This application demonstrates how to integrate the Google Drive API into a React application built with Vite and TypeScript. It allows users to authenticate with Google, create files, and list files in their Google Drive.
Authentication Method: This project uses the Google Identity Services (GIS) library for OAuth 2.0 authentication. The required scripts are loaded in the index.html file and must be included in any project implementing this authentication/service pattern.
- Node.js: Version 14 or higher
- npm: Version 6 or higher
- Google Account: Required for setting up Google API credentials
git clone https://github.com/gitbrent/google-drive-api.git
cd google-drive-apinpm installTo use the Google Drive API, you need to set up a project in the Google Cloud Console and obtain OAuth 2.0 credentials.
Important: This project uses Google Identity Services (GIS) for authentication. Before setting up credentials, ensure that both the GIS and Google API scripts are included in your project's index.html file (see index.html Script Configuration below).
- Go to the Google Cloud Console.
- Sign in with your Google account if you haven't already.
- Click on the project dropdown at the top of the page and select New Project.
- Enter a project name (e.g.,
My React App) and click Create.
- Navigate to APIs & Services > Library in the left sidebar.
- Search for Google Drive API in the search bar.
- Click on Google Drive API from the search results.
- Click on the Enable button.
- Go to APIs & Services > OAuth consent screen.
- Select External for the user type and click Create.
- Fill out the required fields:
- App Name: Your application's name.
- User Support Email: Your email address.
- Developer Contact Information: Your email address.
- Click Save and Continue.
- Scopes: Click Add or Remove Scopes.
- Add the following scope:
https://www.googleapis.com/auth/drive.file
- Add the following scope:
- Click Update and then Save and Continue through the remaining steps.
- Back on the OAuth consent screen, make sure to Publish the app if required.
- Navigate to APIs & Services > Credentials.
- Click on Create Credentials and select OAuth client ID.
- Choose Web Application as the application type.
- Enter a name for the client (e.g.,
React App Client). - Under Authorized JavaScript Origins, add:
http://localhost:5173(adjust if your development server runs on a different port)
- Leave Authorized Redirect URIs empty (unless specifically needed).
- Click Create.
- Copy the Client ID and Client Secret.
While GAPI can theoretically work with just an Auth Token, providing an API Key is recommended to handle quota management and public file access reliably.
- In APIs & Services > Credentials, click on Create Credentials and select API key.
- Copy the generated API Key.
Create a .env file in the root directory of your project to store environment variables.
touch .envAdd the following environment variables to your .env file:
VITE_GOOGLE_CLIENT_ID=your-google-client-id
VITE_GOOGLE_API_KEY=your-google-api-key- Replace
your-google-client-idwith the Client ID obtained from the Google Cloud Console. - Replace
your-google-api-keywith the API Key if you obtained one. If not using an API key, you can omit this line or leave it empty.
Important: Ensure that the .env file is included in your .gitignore file to prevent sensitive information from being committed to version control.
Start the development server:
npm run devOpen your browser and navigate to http://localhost:5173 to view the application.
Critical Step: This project requires two external Google scripts to be included in your index.html file. These scripts must be present for authentication and API operations to function correctly.
In the <head> section of your index.html, include:
<!-- Google Identity Services (GIS) - Required for OAuth 2.0 Authentication -->
<script src="https://accounts.google.com/gsi/client" async defer></script>
<!-- Google API Client Library - Required for Google Drive API Operations -->
<script src="https://apis.google.com/js/api.js" async defer></script>Important: If you're implementing this authentication/service pattern in another project, you must include these exact script tags in your project's index.html file. Without these scripts, authentication will fail and API operations will not work.
your-project/
├── .env
├── .gitignore
├── index.html ⚠️ Contains GIS and GAPI scripts
├── package.json
├── tsconfig.json
├── vite.config.ts
├── public/
│ └── (optional static assets)
└── src/
├── main.tsx
├── App.tsx
├── services/
│ ├── auth.ts (GIS authentication logic)
│ └── googleApi.ts (Google Drive API operations)
├── context/
│ ├── AuthContext.ts (Authentication state type definitions)
│ └── AuthProvider.tsx (Authentication state management)
├── components/
│ └── MainPage.tsx
├── types/
│ └── DriveFile.ts
├── assets/
└── styles/
index.html:⚠️ Critical - Contains the required Google Identity Services and Google API scripts. Any project using this authentication pattern must include these scripts.src/main.tsx: Entry point of the React application.src/App.tsx: Root component that initializes authentication and wraps the application withAuthProvider.src/services/auth.ts: Contains GIS authentication logic and user sign-in/sign-out functions.src/services/googleApi.ts: Contains functions to initialize the Google API client and interact with Google Drive (e.g.,loadGoogleAPIs,createFile,listFiles).src/context/AuthContext.ts: Defines TypeScript types for authentication state.src/context/AuthProvider.tsx: Implements React Context for managing authentication state across the app.src/components/MainPage.tsx: Main component where users interact with the app, including signing in/out and performing file operations.src/types/DriveFile.ts: TypeScript interfaces and types for Google Drive file objects and API responses.src/styles/: Directory for styling files (CSS).src/assets/: Directory for static assets like images or fonts.
In the project directory, you can run:
npm run dev: Runs the app in development mode with hot module replacement.npm run build: Builds the app for production.npm run preview: Serves the production build locally for preview.npm run lint: Lints the codebase using ESLint (if configured).npm run format: Formats the codebase using Prettier (if configured).
Make sure your .env file is properly configured with your Google credentials:
VITE_GOOGLE_CLIENT_ID=your-google-client-id
VITE_GOOGLE_API_KEY=your-google-api-keyRestart your development server after updating environment variables for changes to take effect.
This project includes Bootstrap for styling components. Bootstrap CSS is already installed as a dependency.
To use Bootstrap in your application, import the Bootstrap CSS in your src/main.tsx file:
import 'bootstrap/dist/css/bootstrap.min.css';You can then use Bootstrap utility classes and components directly in your JSX.
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
If you are developing a production application, we recommend updating the configuration to enable type-aware lint rules:
-
Configure the top-level
parserOptionsproperty like this:// eslint.config.js export default { parserOptions: { project: ['./tsconfig.json'], tsconfigRootDir: __dirname, }, // ...other configurations };
-
Replace
eslint:recommendedwithplugin:@typescript-eslint/recommendedorplugin:@typescript-eslint/recommended-requiring-type-checkingin your ESLint configuration. -
Install
eslint-plugin-reactand update the config:npm install --save-dev eslint-plugin-react
// eslint.config.js module.exports = { // ...other configurations plugins: ['react'], extends: [ // ...other extends 'plugin:react/recommended', ], settings: { react: { version: 'detect', }, }, };
-
Optionally, add
eslint-config-prettierto disable ESLint rules that might conflict with Prettier:npm install --save-dev eslint-config-prettier
// eslint.config.js module.exports = { // ...other configurations extends: [ // ...other extends 'eslint:recommended', 'plugin:@typescript-eslint/recommended', 'plugin:react/recommended', 'prettier', ], };
This project is licensed under the MIT License - see the LICENSE file for details.
- Scripts Not Loading: If authentication fails or the Google API is unavailable, verify that both scripts in
index.htmlare properly loaded. Check browser console for CORS or network errors. - Script Loading Order: Ensure the GIS script (
https://accounts.google.com/gsi/client) is loaded before attempting to usewindow.google.accounts.id. - Replication Required: When implementing this pattern in a new project, you must include both scripts in your
index.htmlfile. Simply copying the service files is not sufficient.
- Environment Variables: Remember to restart your development server after changing environment variables.
- OAuth Consent Screen: If you encounter an "Unverified App" warning, you may need to publish your app or add test users in the OAuth consent screen settings.
- API Quotas: Monitor your API usage in the Google Cloud Console to ensure you stay within free tier limits.
- Multiple Google Accounts: If you're signed into multiple Google accounts, ensure you're granting permissions with the correct account.
- CORS Issues: Ensure that your
Authorized JavaScript originsin the Google Cloud Console match the origin from which your app is served (e.g.,http://localhost:5173for local development).
If you have any questions or need further assistance, feel free to open an issue or contact the maintainer.

