Add Sign in with Google to your React and Node Application

You most likely want users to be able to quickly log in to your modern web application without having to remember another password. This guide will show you how to set up Google Authentication with React and Node.js in a clear, production-ready manner and add Google Sign-in to your React and Node application. You will learn how to use a straightforward flow to implement Google authentication in React and Node.js: the Node.js backend verifies the Google token, stores the user in MongoDB, and issues a JWT, while the React frontend handles the Google button. You will have a complete React Google login with Express backend example by the end, which you can use for other projects.

Why implement Google authentication in your React and Node app

Consider the applications you use every day – project managers, learning platforms, or booking websites. The Continue with Google button is common in most of these applications because it is frictionless and gains the trust of clients.

When you integrate Google Sign In with React and Node.js, you provide a very familiar and secure experience for accessing your application. Users will be able to utilize functionality on your application in only a matter of seconds rather than going through a very lengthy sign up form.

Key benefits of Login with Google

  • Faster sign‑up and sign‑in, which improves conversion rates
  • Fewer passwords to remember, so users feel less frustrated
  • Better security because Google handles password storage and 2FA
  • Higher trust, as people already know and rely on Google’s login flow
  • Cleaner user profiles with verified email addresses and names
  • Easier onboarding on mobile and desktop with a consistent experience

Generating your Google OAuth client ID (API key)

To enable Google Authentication with React and Node.js, you first create a Google OAuth client ID.

  1. Go to Google Cloud Console: https://console.cloud.google.com
  2. Create a new project or pick an existing one
  3. Open APIs & Services → OAuth consent screen, choose External, fill details, and save
  4. Go to Credentials → Create credentials → OAuth client ID
  5. Select Web application and add authorised JavaScript origins, for example: http://localhost:3000/

We will use this client ID into react app for showing google login screen and for checking user details on Node.js

Frontend implementation of Login with Google in React

Now you will add the actual “Sign in with Google” button to your React app. This section is the heart of any guide on how to implement Google authentication in React and Node.js. We will use the @react-oauth/google package, which provides a modern wrapper around the latest Google Identity Services.

In your React project folder, install the required packages:

npm install @react-oauth/google axios

Setting up the Google Login button in React

Wrap your app with GoogleOAuthProvider so every component can use the Google login. For a Vite or modern React setup, you might have a main.jsx or index.jsx file:

import React from 'react'
import ReactDOM from 'react-dom/client'
import { GoogleOAuthProvider } from '@react-oauth/google'
import App from './App'

ReactDOM.createRoot(document.getElementById('root')).render(
  <GoogleOAuthProvider clientId="YOUR_GOOGLE_CLIENT_ID">
    <App />
  </GoogleOAuthProvider>
)

Now create or update App.jsx to use the GoogleLogin component and send the Google credential to your Node backend:

import React, { useState } from 'react'
import { GoogleLogin } from '@react-oauth/google'
import axios from 'axios'

function App() {
  const [user, setUser] = useState(null)

  const handleSuccess = async credentialResponse => {
    try {
      const res = await axios.post('http://localhost:5000/api/auth/google', {
        credential: credentialResponse.credential
      })

      localStorage.setItem('token', res.data.token)
      setUser(res.data.user)
    } catch (error) {
      console.error(error)
    }
  }

  const handleError = () => {
    console.error('Google login failed')
  }

  return (
    <div>
      <h1>Add Sign in with Google to your React and Node Application</h1>

      {!user && (
        <GoogleLogin onSuccess={handleSuccess} onError={handleError} />
      )}

      {user && (
        <div>
          <p>Welcome, {user.name}</p>
          <img src={user.avatar} alt={user.name} width={48} height={48} />
        </div>
      )}
    </div>
  )
}

export default App

In practical case, this flow feels very natural: a new user clicks the Google button, your frontend receives a secure credential, sends it to the server, and then shows a personalised dashboard after the server confirms the login.

Node.js implementation of Google Authentication

Now, we will build the backend part of this Google authentication React Node.js JWT. In this step, your Node.js and Express backend will verify the Google ID token using the official Google Auth library, then create a new user in MongoDB or find an existing one. After that, it will generate a signed JWT for the authenticated user and return both the JWT and basic user profile data to the frontend. This gives you a clean react Google login with Express backend example that you can easily adapt to different projects or production environments.

Installing packages

Create a new Node.js project or use existing one and install the required dependencies:

npm install express cors dotenv mongoose jsonwebtoken google-auth-library

You can keep your frontend and backend in one repository or separate them; both approaches work well in practice.

MongoDB connection and User model

Create a file named .env in your backend folder:

PORT=5000
MONGODB_URI=mongodb+srv://your_user:your_password@your-cluster.mongodb.net/google-auth-demo
GOOGLE_CLIENT_ID=YOUR_GOOGLE_CLIENT_ID
JWT_SECRET=your_jwt_secret_key

Now create models/User.js for your user schema:

const mongoose = require('mongoose')

const userSchema = new mongoose.Schema(
  {
    googleId: { type: String, required: true, unique: true },
    email: { type: String, required: true, unique: true },
    name: { type: String },
    avatar: { type: String }
  },
  { timestamps: true }
)

module.exports = mongoose.model('User', userSchema)

This structure keeps only essential data: the Google id, email, name, and avatar. In a real product, you can extend this with roles, preferences, or billing fields as your app grows.

Building the Express backend for Google login

Now create server.js in your backend folder. This file wires up Express, connects to MongoDB, verifies Google tokens, and issues JWTs.

const express = require('express')
const cors = require('cors')
const dotenv = require('dotenv')
const mongoose = require('mongoose')
const jwt = require('jsonwebtoken')
const { OAuth2Client } = require('google-auth-library')
const User = require('./models/User')

dotenv.config()

const app = express()

app.use(cors({ origin: 'http://localhost:5173', credentials: true }))
app.use(express.json())

mongoose
  .connect(process.env.MONGODB_URI)
  .then(() => console.log('MongoDB connected'))
  .catch(error => console.error(error))

const client = new OAuth2Client(process.env.GOOGLE_CLIENT_ID)

app.post('/api/auth/google', async (req, res) => {
  try {
    const { credential } = req.body

    const ticket = await client.verifyIdToken({
      idToken: credential,
      audience: process.env.GOOGLE_CLIENT_ID
    })

    const payload = ticket.getPayload()
    const { sub, email, name, picture } = payload

    let user = await User.findOne({ googleId: sub })

    if (!user) {
      user = await User.create({
        googleId: sub,
        email,
        name,
        avatar: picture
      })
    }

    const token = jwt.sign(
      { userId: user._id },
      process.env.JWT_SECRET,
      { expiresIn: '7d' }
    )

    res.json({ token, user })
  } catch (error) {
    console.error(error)
    res.status(401).json({ message: 'Authentication failed' })
  }
})

const port = process.env.PORT || 5000

app.listen(port, () => {
  console.log(`Server listening on port ${port}`)
})

You can now run your backend with:

node server.js

Now your Login with Google functionality is completed for both frontend and backend. As for flow, when user visits front end and click on button for login. React will show google consent window and allow user to select account. React will receive google credentials and forward it to backend.

As for backend, express will verify token and create user. At last Node.js will return new JWT token for that user for frontend to keep user loggedin.

Conclusion

You have now mastered the art of integrating Google Sign In with React & Node.js, including writing an efficient login system that feels experience-like for your users. Your Google OAuth 2.0 auth implementation in Node.js/React checks off all the necessary token checks, saves information to MongoDB, and provides JWT for sessions.

You can now secure the private routes using the JWT token in the frontend as well as the backend, implement role-based authorization, or integrate the login functionality with the features in your application. Since Google Authentication with React and Node.js is implemented in your application, the application now appears more professional and secure; it is also simpler for new users to use the application because login functionality would only be done once by creating an account while signing up for the application.