Google login using vue 3 js
and express js
Ajibade tolu
In this tutorial we’ll use google login with vue3-google-
login and vue-google-oauth2 ,I’ll show you how to
send it to a backend(express js)
You can install vue 3 by
Vue create my-project-name
I’m sure you have your vue application running install
this
Npm install vue3-google-login vue-google-
oauth2 axios
Get your oauth details from here
https://console.cloud.google.com/
Vue Component
<template>
<div>
<!—Login Button
<button @click=”login”>Login Using
Google</button>
<!—Display User Details After Successful Login
<div v-if=”userDetails”>
<h2>User Details</h2>
<p>Name: {{ userDetails.name }}</p>
<p>Email: {{ userDetails.email }}</p>
<p>
Profile Picture:
<img :src=”userDetails.picture” alt=”Profile
Picture” />
</p>
</div>
</div>
</template>
Explanation:
1. Login Button: A button is provided for the user to
start the Google Login process.
2. User Details Display: After a successful login and
backend verification, user details (name, email,
and profile picture) are displayed.
Script file for backend configuration
2
<script>
Import { googleSdkLoaded } from “vue3-google-
login”;
// Import SDK loader for Google
Import axios from “axios”;
// Import Axios for making HTTP requests
Export default {
Name: “GoogleLoginComponent”,
Data() {
Return {
userDetails: null,
// Store user details here
};
},
Methods: {
// Method to trigger Google Login flow
Login() {
googleSdkLoaded((google) => {
// Initialize the Google OAuth2 client
Google.accounts.oauth2
.initCodeClient({
Client_id:
“YOUR_CLIENT_ID.apps.googleusercontent.com”, //
Replace with your Google OAuth client ID
Scope: “email profile openid”, // Permissions
requested from the user
Redirect_uri:
http://localhost:4000/auth/callback, // Redirect URI to
your backend
Callback: (response) => {
3
// Callback function after login attempt
If (response.code) {
This.sendCodeToBackend(response.code); //
Send authorization code to the backend
}
},
})
.requestCode(); // Request authorization code
from the user
});
},
// Method to send authorization code to backend
Async sendCodeToBackend(code) {
Try {
Const headers = { Authorization: code }; // Add
the authorization code to headers
// Send a POST request to the backend for
verification
Const response = await
axios.post(http://localhost:4000/auth, null, {
Headers,
});
This.userDetails = response.data; // Update user
details with backend response
} catch (error) {
Console.error(“Failed to send authorization
code:”, error); // Handle errors
}
},
},
};
4
</script>
The above get the code and sends it to the backend
for verification which now returns the user details
Using NODEJS as backend
In your backend folder do
Npm install express axios cors OAuth2Client
Const express = require(‘express’);
Const axios = require(‘axios’);
Const cors = require(‘cors’);
Const { OAuth2Client } = require(‘google-auth-
library’);
Const oauth2Client = new OAuth2Client()
Const app = express();
// Enable CORS for all routes
App.use(cors());
// 1. Call the Google SDK from the frontend using
whatever frontend
//2. Extract the code or access token and send to your
backend for verification.
//3. Use your backend Google api to verify the code or
token.
//4. If verified, sign them in the backend and then send
a response to frontend
App.post(‘/auth’, async (req, res) => {
Try {
// get the code from frontend
Const code = req.headers.authorization;
Console.log(‘Authorization Code:’, code);
5
// Exchange the authorization code for an access
token
Const response = await axios.post(
‘https://oauth2.googleapis.com/token’,
{
Code,
Client_id: ‘587301-
d27f8hofgi6i0.apps.googleusercontent.com’,
Client_secret: ‘GOCSPX-u02eNWutQVi’,
Redirect_uri: ‘postmessage’,
Grant_type: ‘authorization_code’
}
);
Const accessToken = response.data.access_token;
Console.log(‘Access Token:’, accessToken);
// Fetch user details using the access token
Const userResponse = await
axios.get(
‘https://www.googleapis.com/oauth2/v3/userinfo’,
{
Headers: {
Authorization: `Bearer ${accessToken}`
}
}
);
Const userDetails = userResponse.data;
Console.log(‘User Details:’, userDetails);
// Process user details and perform necessary
actions Res.status(200).json({ message:
‘Authentication successful’ });
} catch (error) {
6
Console.error(‘Error saving code:’, error);
Res.status(500).json({ message: ‘Failed to save
code’ });
}
});
App.listen(4000, () => {
Console.log(‘Server running on port 4000’);
});
If you want too Display the user details without a
backend you can use this code
<template>
<div>
<!—Button to trigger Google Login
<button @click=”login”>Login Using
Google</button>
<!—Display user details if the login is successful
<div v-if=”userDetails”>
<h2>User Details</h2>
<p>Name: {{ userDetails.name }}</p>
<p>Email: {{ userDetails.email }}</p>
<p>
Profile Picture:
<img :src=”userDetails.picture” alt=”Profile
Picture” />
</p>
</div>
</div>
</template>
7
1. Login Button: When clicked, it calls the login
method in the script.
2. Conditional Rendering:if userDetails is populated
(i.e., after successful login), the user’s name,
email, and profile picture are displayed.
Script section
<script>
Import { googleSdkLoaded } from “vue3-google-
login”; // Import the Google SDK loader
Import axios from “axios”; // Import Axios for HTTP
requests
Export default {
Data() {
Return {
userDetails: null, // Stores user details after login
};
},
Name: “YourComponent”, // Component name
Methods: {
// Method to handle Google Login
Login() {
googleSdkLoaded((google) => {
// Initialize the Google OAuth client
Google.accounts.oauth2
.initCodeClient({
Client_id: “586701-
d2i0.apps.googleusercontent.com”, // Replace with
your Google OAuth client ID
8
Scope: “email profile openid”, // Permissions
requested from the user
Redirect_uri:
http://localhost:4000/auth/callback, // Backend URL to
handle callback
Callback: (response) => {
// Handle the response after login
If (response.code) {
This.sendCodeToBackend(response.code); //
Send the authorization code to the backend
}
},
})
.requestCode(); // Request the authorization
code
});
},
// Send the authorization code to the backend and
exchange for an access token
Async sendCodeToBackend(code) {
Try {
// Make a POST request to exchange the
authorization code for an access token
Const response = await axios.post(
https://oauth2.googleapis.com/token,
{
Code, // Authorization code from Google
Client_id: “58730101-
di0.apps.googleusercontent.com”, // Your Google
Client ID
9
Client_secret: “GOCSPX-u02eNidw0DqWutQVi”,
// Your Google Client Secret
Redirect_uri: “postmessage”, // Specifies that
the response should remain on the client
Grant_type: “authorization_code”, // Indicates
that this is an authorization code exchange
}
);
// Access token received from the response
Const accessToken =
response.data.access_token;
Console.log(accessToken); // Log the token for
debugging purposes
// Use the access token to fetch user details
Const userResponse = await axios.get(
https://www.googleapis.com/oauth2/v3/userinfo,
{
Headers: {
Authorization: `Bearer ${accessToken}`, //
Pass the token in the Authorization header
},
}
);
If (userResponse && userResponse.data) {
// Set the fetched user details to the userDetails
property
This.userDetails = userResponse.data;
} else {
10
Console.error(“Failed to fetch user details.”); //
Log an error if fetching user details fails
}
} catch (error) {
Console.error(“Token exchange failed:”,
error.response.data); // Log errors during token
exchange
}
},
},
};
</script>
11
12