DEV Community

Devlink Tips
Devlink Tips

Posted on

How to Connect Next.js to Google Drive: A Full Guide

This post shows how to connect Google Drive to Next.js. It addresses developing a basic UI to show saved documents, configuring NextAuth.js for authentication, creating API routes to retrieve Google Drive data, and by the conclusion, you’ll be able to safely handle OAuth-based API calls, authenticate users with Google, and get files from Google Drive using Next.js.

Google Drive is a popular cloud storage service. If you connect it to your Next.js app, users will be able to easily view, upload, and manage their files. You can use Google Drive’s API to make a secure and scalable document management system, a file-sharing tool, or a cloud-based note-taking app.

Before getting started, make sure you have:
Make sure you have these things before you start:
You have set up a Next.js project (npx create-next-app my-app).
An account on Google Cloud Console to make OAuth credentials
Your Google project must have the Google Drive API turned on.
Know the basics of OAuth 2.0 and Next.js API routes.

Step 1: Enable Google Drive API and Create OAuth Credentials

You need to make OAuth passwords and enable the Google Drive API to use Google Drive from Next.js.

Set up a new project in the Google Cloud Console.

To find the Google Drive API, go to API & Services > Enable APIs & Services.
Then search for it and turn it on.

Make a new OAuth 2.0 client ID in Credentials:

You can pick Web Application as the type of app.

To test it, set your redirect URI to http://localhost:3000/api/auth/callback/google.

Remember to write down the Client ID and Client Secret.

Step 2: Install Dependencies

To link Google Drive to your Next.js project, you will need several really essential packages. The first one is NextAuth.js; it helps your app correctly manage OAuth, allowing login. Second, Google APIs enable you to use Google Drive among other Google products.

npm install next-auth googleapis
Enter fullscreen mode Exit fullscreen mode

Google APIs will enable API searches to access Google Drive data; NextAuth.js will let Google manage user authentication following installation. These two apps authenticate users and retrieve access tokens; the Google APIs package uses those tokens to make safe searches of Google Drive. With these dependencies set up, your Next.js app will be ready for simple Google Drive linking.

Step 3: Configure NextAuth.js for Google Authentication.

To use Google Consumer Authentication, make a NextAuth.js configuration file in pages/api/auth/[…nextauth]:

import NextAuth from "next-auth";
import GoogleProvider from "next-auth/providers/google";

export default NextAuth({
  providers: [
    GoogleProvider({
      clientId: process.env.GOOGLE_CLIENT_ID,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET,
      authorization: {
        params: {
          scope: "openid email profile https://www.googleapis.com/auth/drive.readonly",
        },
      },
    }),
  ],
  callbacks: {
    async session({ session, token }) {
      session.accessToken = token.accessToken;
      return session;
    },
    async jwt({ token, account }) {
      if (account) {
        token.accessToken = account.access_token;
      }
      return token;
    },
  },
});
Enter fullscreen mode Exit fullscreen mode

Important things about this arrangement

Google Producer: Made it possible to log in to Google.

Setting the Scope: Allow people to read only in Google Drive.

Running Sessions: keeps the OAuth code in the session so that API access is possible.

Step 4: Create an API Route to Fetch Google Drive Files

Establish an API route in Pages JavaScriptJavaScript/api/drive.js to access Google Drive.

import { google } from "googleapis";
import { getSession } from "next-auth/react";

export default async function handler(req, res) {
  const session = await getSession({ req });

  if (!session || !session.accessToken) {
    return res.status(401).json({ error: "Unauthorized" });
  }

  const auth = new google.auth.OAuth2();
  auth.setCredentials({ access_token: session.accessToken });

  const drive = google.drive({ version: "v3", auth });

  try {
    const response = await drive.files.list({
      pageSize: 10,
      fields: "files(id, name, mimeType)",
    });

    res.status(200).json(response.data.files);
  } catch (error) {
    res.status(500).json({ error: "Failed to fetch files" });
  }
}
Enter fullscreen mode Exit fullscreen mode

What This API Route Does?

verifies the user’s authentication.

Access Google Drive using the saved OAuth token.

retrieves from the user’s Google Drive the file list.

Step 5: Build a UI to Display Google Drive Files

Please update your Next.js component (pages/index.js) to display the retrieved Google Drive files.

import { useSession, signIn, signOut } from "next-auth/react";
import { useEffect, useState } from "react";

export default function Home() {
  const { data: session } = useSession();
  const [files, setFiles] = useState([]);

  useEffect(() => {
    if (session) {
      fetch("/api/drive")
        .then((res) => res.json())
        .then((data) => setFiles(data));
    }
  }, [session]);

  return (
    <div>
      {session ? (
        <>
          <p>Welcome, {session.user.name}</p>
          <button onClick={() => signOut()}>Sign Out</button>
          <h2>Your Google Drive Files:</h2>
          <ul>
            {files.map((file) => (
              <li key={file.id}>{file.name} ({file.mimeType})</li>
            ))}
          </ul>
        </>
      ) : (
        <button onClick={() => signIn("google")}>Sign In with Google</button>
      )}
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

How This Is Done

The system displays a sign-in button in the event that the user lacks authentication.

Should one sign in, it shows files from Google Drive.

The system displays a sign-out button to call off the session.

Step 6: Secure Your API and Deployment

Store credentials securely in:.env.local

GOOGLE_CLIENT_ID=your-client-id
GOOGLE_CLIENT_SECRET=your-client-secret
NEXTAUTH_SECRET=your-random-secret
Enter fullscreen mode Exit fullscreen mode

Deploy the Next.js app using Vercel or your preferred hosting provider.

Conclusion

This post will show you how to connect Google Drive to Next.js by setting up NextAuth.js for authentication, making API routes to access Drive, and making a simple UI to show files. From this vantage point, it’s simple to start initiatives for maintaining personal screens, file storage, or methods of sharing files.

Further Reading:

NextAuth.js Documentation

Google Drive API Reference

OAuth 2.0 Overview

You can create a properly working Google Drive-powered program by including the appropriate security measures and extending this configuration.

Top comments (0)