How To Integrate with Google APIs from a Nextjs App Backend

3 min read 2 hours ago
Published on Oct 16, 2024 This response is partially generated with the help of AI. It may contain inaccuracies.

Table of Contents

Introduction

This tutorial will guide you through the process of integrating Google APIs into a Next.js application using OAuth 2.0 for authentication. We will utilize the official Google API client library to manage authentication and API requests. By the end of this tutorial, you'll be able to authenticate users, manage authorization, and call the Google Drive API to list documents.

Step 1: Set Up Google Cloud Console

  1. Go to the Google Cloud Console.
  2. Create a new project:
    • Click on the project dropdown and select "New Project".
    • Enter a project name and click "Create".
  3. Enable Google APIs:
    • Navigate to "Library" in the left menu.
    • Search for APIs you need (like Google Drive API) and enable them for your project.
  4. Set up OAuth 2.0 credentials:
    • Go to "APIs & Services" > "Credentials".
    • Click on "Create Credentials" and select "OAuth client ID".
    • Configure the consent screen with necessary information.
    • Choose "Web application" as the application type.
    • Add authorized redirect URIs (e.g., http://localhost:3000/api/auth/callback).
    • Save your client ID and client secret for later use.

Step 2: Initialize Your Next.js Application

  1. Create a new Next.js app if you haven't done so:
    npx create-next-app@latest your-app-name
    cd your-app-name
    
  2. Install the Google API client library:
    npm install googleapis
    
  3. Set up your project structure:
    • Create an api folder inside the pages directory for your backend APIs.

Step 3: Implement OAuth 2.0 Authentication

  1. Create a new file auth.js inside the pages/api directory.
  2. Set up the authentication logic using the Google API client:
    const { google } = require('googleapis');
    const OAuth2 = google.auth.OAuth2;
    
    const oauth2Client = new OAuth2(
        YOUR_CLIENT_ID,
        YOUR_CLIENT_SECRET,
        YOUR_REDIRECT_URL
    );
    
    function getAuthUrl() {
        const scopes = ['https://www.googleapis.com/auth/drive.metadata.readonly'];
        return oauth2Client.generateAuthUrl({ access_type: 'offline', scope: scopes });
    }
    
    export default function handler(req, res) {
        if (req.method === 'GET') {
            const url = getAuthUrl();
            res.redirect(url);
        }
    }
    
  3. Replace YOUR_CLIENT_ID, YOUR_CLIENT_SECRET, and YOUR_REDIRECT_URL with your actual credentials.

Step 4: Handle the OAuth Callback

  1. Create a new file callback.js inside the pages/api directory.
  2. Implement the logic to handle the redirect after authentication:
    export default async function handler(req, res) {
        const { code } = req.query;
        const { tokens } = await oauth2Client.getToken(code);
        oauth2Client.setCredentials(tokens);
        // Store tokens in cookies or session
        res.redirect('/');
    }
    

Step 5: Call the Google Drive API

  1. Create a new function to list documents from Google Drive:
    async function listFiles(auth) {
        const drive = google.drive({ version: 'v3', auth });
        const response = await drive.files.list({
            pageSize: 10,
            fields: 'nextPageToken, files(id, name)',
        });
        return response.data.files;
    }
    
  2. Call this function in your main app file to display the files.

Conclusion

In this tutorial, we covered how to integrate Google APIs with a Next.js application using OAuth 2.0. We set up the Google Cloud Console, initialized a Next.js app, implemented authentication, handled callbacks, and called the Google Drive API. For further exploration, check the official documentation for more Google APIs and consider building additional features into your application.