Connect React/Next.js to Google Drive API (V3) for File Upload, Search & Retrieval
Learn how to seamlessly integrate Google Drive API with Next.js (or React.js) to upload and retrieve files in your web applications. This step-by-step guide covers setting up Google Cloud credentials, implementing file upload functionality, and retrieving stored files, making it easy for developers to enhance their applications with Google Drive integration. Perfect for developers looking to leverage cloud storage in their Next.js or React.js projects.

Step-by-Step Guide to Get Google Drive Service Account Credentials for File Uploading
Create a New Project on Google Cloud Platform
Go to the Google Cloud Console: Google Cloud Console.
Create a New Project:
- Click on the project dropdown in the top navigation bar.
- Click on “New Project”.
- Enter a name for your project and click “Create”.Enable Google Drive API
Navigate to the API Library:
- In the left-hand menu, go to APIs & Services > Library.
- Enable Google Drive API:
- Search for “Google Drive API”.
- Click on it and then click “Enable”.Create a Service Account
- Navigate to the Service Accounts Page:
- Go to APIs & Services > Credentials.
- Click on Create Credentials and select Service Account.
- Fill in the Details:
- Enter a name for the service account and an optional description.
- Click Create and continue.
- Grant the Service Account Permissions:
- You can skip this step or assign specific roles if needed.
- Click Continue.
- Create a Key:
- In the Keys section, click Add Key > Create New Key.
- Choose JSON and click Create.
The JSON key file will be downloaded to your computer. Keep it safe, as it contains the credentials you will need.
Use the Service Account Credentials in Your Next.js or React.js Application
Install the googleapis
library in your project using npm or yarn
npm install googleapis
Set up .env file and add values from your json file that we downloaded from google cloud console
TYPE =
PROJECT_ID =
PRIVATE_KEY_ID =
PRIVATE_KEY =
CLIENT_EMAIL =
CLIENT_ID =
AUTH_URI =
TOKEN_URI =
AUTH_PROVIDER_X509_CERT_URL =
CLIENT_X509_CERT_URL =
UNIVERSE_DOMAIN =
Create a new file upload-to-drive.js and use the below code
"use server"; // if you are using reactjs remove this line this is for nextjs only
import { google } from "googleapis";
import { Readable } from "stream";
export const findExistingFile = async (driveService, fileName) => {
try {
const response = await driveService.files.list({
q: `name='${fileName}'`,
fields: "files(id, webViewLink)",
});const files = response.data.files;
if (files && files.length > 0) {
return files[0]; // Return the first matching file
} else {
return null; // File not found
}
} catch (error) {
console.error("Error searching for file:", error);
throw error;
}
};
export const uploadToGooglDrive = async (file) => {
const auth = new google.auth.GoogleAuth({
credentials: {
type: process.env.TYPE,
project_id: process.env.PROJECT_ID,
private_key_id: process.env.PRIVATE_KEY_ID,
private_key: process.env.PRIVATE_KEY.replace(/\\n/g, '\n'),
client_email: process.env.CLIENT_EMAIL,
client_id: process.env.CLIENT_ID,
auth_uri: process.env.AUTH_URI,
token_uri: process.env.TOKEN_URI,
auth_provider_x509_cert_url: process.env.AUTH_PROVIDER_X509_CERT_URL,
client_x509_cert_url: process.env.CLIENT_X509_CERT_URL,
universe_domain: process.env.UNIVERSE_DOMAIN,
},
scopes: ["https://www.googleapis.com/auth/drive"],
});
const fileBuffer = file.stream();
const fileMetadata = {
name: file.name,
};
const driveService = google.drive({ version: "v3", auth });
const existingFile = await findExistingFile(driveService, file.name);
if (existingFile) {
const viewLink = existingFile.webViewLink
return { viewLink: viewLink, success: true, };
}
const response = await driveService.files.create({
requestBody: fileMetadata,
media: {
mimeType: "application/pdf",
body: Readable.from(fileBuffer)
},
fields: "id, webViewLink",
});const docId = response.data.id;
const viewLink = response.data.webViewLink;
console.log(`File '${file.name}' uploaded with ID: ${docId}`);
console.log(`View link: ${viewLink}`);
// Add permissions
await driveService.permissions.create({
fileId: docId,
requestBody: {
role: "reader",
type: "anyone",
},
});
await driveService.permissions.create({
fileId: docId,
requestBody: {
role: "writer",
type: "user",
emailAddress: "<your email address with which You want to share this file on google drive>",
},
});
const newFileviewLink = response.data.webViewLink
return { viewLink: newFileviewLink, success: true, };
}
Summary of above code
Find Existing File: Checks if a file already exists on Google Drive. You can skip this part by removing this line from code
// remove this code if you don't want to check if file is already uploaded or not
const existingFile = await findExistingFile(driveService, file.name);
if (existingFile) {
const viewLink = existingFile.webViewLink
return { viewLink: viewLink, success: true, };
}
uploadToGooglDrive: Uploads a file to Google Drive, checks for existing files, uploads if necessary, and sets permissions on the file. It uses the Google Drive API and streams the file data for efficient uploading.
Important :
we are adding permissions to the uploaded file in this part of code , making it readable by anyone and writable by a specific user for example if you are passing your personal Gmail in email address you can view the uploaded files on that particular mail drive account so it is important to add a emailAddress
await driveService.permissions.create({
fileId: docId,
requestBody: {
role: "writer",
type: "user",
emailAddress: "Your Gmail id",
},
});
💥 Did you find this blog helpful? 💥
If you enjoyed this post, please clap and follow for more insights on web development and Next.js! Your support helps me continue sharing useful content to enhance your development journey. 🚀
Written by Sagar Sangwan
👨💻 Programmer | ✈️ Love Traveling | 🍳 Enjoy Cooking | Building cool tech and exploring the world!
View more blogs by me CLICK HERE
Loading related blogs...
SUBSCRIBE to Newsletter
In this newsletter we provide latest news about technology, business and startup ideas. Hope you like it.