Integrating Gmail API in a React App: A Step-by-Step Guide for Fetching and Displaying Emails

Mirza Anees Baig Barlas
5 min readSep 25, 2024

--

First we need to set up google developer console

To set up the Google Developer Console for your React app with Google Sign-In and Gmail API access, follow these steps:

Visit the Google Developer Console:

https://console.developers.google.com

Create a new project:

Click on the project dropdown next to the “Google Cloud Platform” logo in the top-left corner.

Click on the “New Project” button at the top-right of the modal that appears.

Enter a project name, select a billing account if necessary, and choose an organization and location (if applicable). d. Click the “Create” button.

Now click APIs and services in management section

Click ENABLE APIS AND SERVICES

Enable Google+ API

Now search for Google+ API and click it

Click Google+

Click enable

You will now see this window

Enable Gmail API

Now search for Gmail API and click it

Click Gmail API

Click Enable

Now Gmail Api is also set up now click CREATE CREDENTIALS

Click Next

Fill all required fields and click SAVE AND CONTINUE

Skip scopes as it is optional

Now in OAuth Client ID

Choose “Web application” as the application type.

Enter a name for your OAuth client.

Set the “Authorized JavaScript origins” to your app’s domain (e.g., http://localhost & http://localhost:3000 for local development).

Set the “Authorized redirect URIs” to the same domain as the JavaScript origins, but with /oauth2callback appended (e.g., http://localhost:3000/oauth2callback for local development).

Fill info and click CREATE

You will now get Client ID copy and save it and click DONE

Now you are all set

Now go to your project and I am setting everything up in App.js but you can create your own reusable component

Install gapi-script from npmjs

npm install gapi-script

create .env and add these variable

Now Copy the code and write it in your component

import React, { useEffect, useState } from 'react';
import { gapi } from 'gapi-script';

const CLIENT_ID = process.env.REACT_APP_GOOGLE_CLIENT_ID;
const API_KEY = process.env.REACT_APP_GOOGLE_API_KEY;
const SCOPES = 'https://www.googleapis.com/auth/gmail.readonly';

const App = () => {
const [isAuthenticated, setIsAuthenticated] = useState(false);
const [messages, setMessages] = useState([]);

useEffect(() => {
const initClient = () => {
gapi.client.init({
apiKey: API_KEY,
clientId: CLIENT_ID,
discoveryDocs: ['https://www.googleapis.com/discovery/v1/apis/gmail/v1/rest'],
scope: SCOPES,
}).then(() => {
gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);
updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
});
};

gapi.load('client:auth2', initClient);
}, []);

const updateSigninStatus = (isSignedIn) => {
setIsAuthenticated(isSignedIn);
if (isSignedIn) {
fetchMessages();
}
};

const handleAuthClick = () => {
gapi.auth2.getAuthInstance().signIn();
};

const handleSignoutClick = () => {
gapi.auth2.getAuthInstance().signOut();
};

const fetchMessages = () => {
gapi.client.gmail.users.messages.list({
userId: 'me',
maxResults: 10,
}).then((response) => {
const messages = response.result.messages;
if (messages && messages.length > 0) {
const messagePromises = messages.map((msg) =>
gapi.client.gmail.users.messages.get({
userId: 'me',
id: msg.id,
})
);

Promise.all(messagePromises).then((responses) => {
const messageDetails = responses.map((res) => res.result);
setMessages(messageDetails);
});
}
});
};

return (
<div>
{!isAuthenticated ? (
<button onClick={handleAuthClick}>Sign in with Google</button>
) : (
<>
<button onClick={handleSignoutClick}>Sign out</button>
<div>
<h2>Your Messages:</h2>
{messages.map((message, index) => (
<div key={index}>
<p>Subject: {message.payload.headers.find(header => header.name === 'Subject')?.value}</p>
<p>From: {message.payload.headers.find(header => header.name === 'From')?.value}</p>
</div>
))}
</div>
</>
)}
</div>
);
};

export default App;

You can change code and scope according to your requirements this is just a basic example i am sharing

Now start your dev server and it will work in web browser

Change the UI according to your needs, what I am sharing here is just an implementation and this step by step guide is not about UI, so I am not doing any css code here

I will also add this code in a repository in github so feel free to make any changes and create PR

--

--

No responses yet