Implementing Google Login in a Node.js Application

Tasadduq Ali
3 min readJul 12, 2023

--

To implement Google Login, you need to set up a Google API project. Follow these steps:

  1. Go to the Google Developers Console (**https://console.developers.google.com/**).
  2. Create a new project or select an existing one.
  3. Enable the "Google+ API" for your project.
  4. Navigate to the "Credentials" section and click on "Create Credentials."
  5. Choose "OAuth client ID" as the credential type.
  6. Select "Web application" as the application type.
  7. Enter a name for your OAuth client ID.
  8. Add authorized JavaScript origins (e.g., http://localhost:3000) and redirect URIs (e.g., **http://localhost:3000/auth/google/callback**).
  9. Click "Create" to generate the client ID and client secret.

Step 2: Set Up the Node.js Project

Start by setting up a new Node.js project using a package manager like npm or yarn. Run the following command in your terminal:

csharpCopy code
npm init

This will create a package.json file to manage your project's dependencies.

Step 3: Install Required Packages

To implement Google Login in Node.js, we need to install the necessary packages. Run the following command in your terminal:

Copy code
npm install express axios

This will install Express.js, a popular Node.js web framework, and the axios package, which we will use to make HTTP requests.

Step 4: Implement the Authentication Routes

Create a new file, authRoutes.js, to define the authentication routes for your application. In this file, implement the routes for initiating the Google Login flow, handling the callback URL, and logging out the user.

javascriptCopy code
const express = require('express');
const axios = require('axios');
const router = express.Router();

const CLIENT_ID = 'YOUR_CLIENT_ID';
const CLIENT_SECRET = 'YOUR_CLIENT_SECRET';
const REDIRECT_URI = '<http://localhost:3000/auth/google/callback>';

// Initiates the Google Login flow
router.get('/auth/google', (req, res) => {
const url = `https://accounts.google.com/o/oauth2/v2/auth?client_id=${CLIENT_ID}&redirect_uri=${REDIRECT_URI}&response_type=code&scope=profile email`;
res.redirect(url);
});

// Callback URL for handling the Google Login response
router.get('/auth/google/callback', async (req, res) => {
const { code } = req.query;

try {
// Exchange authorization code for access token
const { data } = await axios.post('<https://oauth2.googleapis.com/token>', {
client_id: CLIENT_ID,
client_secret: CLIENT_SECRET,
code,
redirect_uri: REDIRECT_URI,
grant_type: 'authorization_code',
});

const { access_token, id_token } = data;

// Use access_token or id_token to fetch user profile
const { data: profile } = await axios.get('<https://www.googleapis.com/oauth2/v1/userinfo>', {
headers: { Authorization: `Bearer ${access_token}` },
});

// Code to handle user authentication and retrieval using the profile data

res.redirect('/');
} catch (error) {
console.error('Error:', error.response.data.error);
res.redirect('/login');
}
});

// Logout route
router.get('/logout', (req, res) => {
// Code to handle user logout
res.redirect('/login');
});

module.exports = router;

Make sure to replace 'YOUR_CLIENT_ID' and 'YOUR_CLIENT_SECRET' with your own credentials obtained from the Google API project.

Step 5: Set Up the Express.js Server

In your main server file (e.g., app.js), import the required packages and configure the Express.js server. Include the authentication routes defined in authRoutes.js.

javascriptCopy code
const express = require('express');
const authRoutes = require('./authRoutes');

const app = express();

app.use('/', authRoutes);

// Start the server
app.listen(3000, () => {
console.log('Server started on port 3000');
});

if you have any questions or suggestions just do let me know on my Instagram or at codeculturepro@gmail.com

--

--

Tasadduq Ali
Tasadduq Ali

Written by Tasadduq Ali

I am MERN Stack developer working in UAE Govt to digitize their massive services. I will help you to become highly skilled Coder 😉