Adding Google Sign-In to a MERN App: From Google Token to Your Own JWT

"Continue with Google" removes one of the biggest drop-off points in any app: making up yet another password. In my Real Estate Marketplace I added Google sign-in alongside normal email-and-password login, with one goal: once a user is signed in, the rest of the app shouldn't care how they signed in.

The trick is to treat Google purely as a way to prove who someone is, then issue your own JWT, the same kind the email/password login issues. Here's the full flow, the code, and the hardening steps I'd recommend.

The flow at a glance

  1. The React app shows a "Continue with Google" button and gets a token from Google.
  2. It sends that token to the Express API (POST /auth/google-login).
  3. The API asks Google who the token belongs to.
  4. The API finds or creates the matching user in MongoDB.
  5. The API signs and returns its own JWT, exactly as the normal login does.

Frontend: the Google button

The @react-oauth/google package handles the Google popup. Wrap the app in <GoogleOAuthProvider clientId={...}>, then use the useGoogleLogin hook:

import { useGoogleLogin } from '@react-oauth/google';

const loginWithGoogle = useGoogleLogin({
  onSuccess: async (tokenResponse) => {
    const res = await API.post('/auth/google-login', {
      accessToken: tokenResponse.access_token,
    });
    localStorage.setItem('token', res.data.token);
    navigate(res.data.user.role === 'admin' ? '/admin-dashboard' : '/');
  },
  onError: () => setError('Google login failed'),
});

// <button onClick={() => loginWithGoogle()}>Continue with Google</button>

A custom hook instead of Google's pre-styled button meant I could match the login page design exactly.

Backend: verify, find or create, issue a JWT

On the server, google-auth-library calls Google's userinfo endpoint with the access token to get the user's profile:

import { OAuth2Client } from 'google-auth-library';
import jwt from 'jsonwebtoken';

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

router.post('/google-login', async (req, res) => {
  try {
    const { accessToken } = req.body;
    if (!accessToken) return res.status(400).json({ error: 'No access token provided' });

    client.setCredentials({ access_token: accessToken });
    const { data } = await client.request({
      url: 'https://www.googleapis.com/oauth2/v3/userinfo',
    });
    const { sub: googleId, email, name, picture: avatar } = data;

    let user = await User.findOne({ email });
    if (!user) {
      user = await User.create({ name, email, googleId, avatar, isOAuthUser: true, role: 'user' });
    } else if (!user.googleId) {
      user.googleId = googleId; // link Google to an existing email/password account
      await user.save();
    }

    const token = jwt.sign({ id: user._id, role: user.role }, process.env.JWT_SECRET, {
      expiresIn: '1d',
    });
    res.json({ token, user: { id: user._id, name: user.name, email: user.email, role: user.role } });
  } catch (err) {
    res.status(500).json({ error: 'Failed to authenticate with Google' });
  }
});

Why issue your own JWT?

Because now every protected route works the same way for every user. The auth middleware only ever verifies your token and reads id and role from it. Google is involved once, at sign-in, and never again. Adding another provider later (GitHub, Apple) means writing one more route that ends in the same jwt.sign(...).

Account linking

If someone registered with email and password and later clicks "Continue with Google" with the same address, they land in the same account, with their Google ID added to it. Without this, people end up with two accounts and "where did my listings go?" support messages.

Hardening it

The flow above works, and these are the improvements I'd make to bring it to production standard.

1. Prefer verifying an ID token

An OAuth access token is meant for calling Google APIs, and it isn't tied to your app. The userinfo endpoint will accept a valid token that was issued to any application. Google's recommended way to sign users in is to verify an ID token, which is signed by Google and carries your client ID as its audience:

// frontend: <GoogleLogin onSuccess={({ credential }) => send(credential)} />
const ticket = await client.verifyIdToken({
  idToken: credential,
  audience: process.env.GOOGLE_CLIENT_ID,
});
const { sub: googleId, email, email_verified, name, picture } = ticket.getPayload();

If you want to keep the custom button and the access-token flow, at least confirm the token was issued for your app before trusting it. client.getTokenInfo(accessToken) returns its audience, which you can compare with your client ID.

2. Only link accounts by a verified email

Linking by email is only safe when Google says the address is verified. Check email_verified (present in both the ID token and the userinfo response) before attaching Google to an existing account.

3. Think about where the JWT lives

Storing the token in localStorage is simple and works well for a SPA, but any script that runs on the page (for example through an XSS bug) can read it. An httpOnly, Secure, SameSite cookie keeps the token out of JavaScript's reach. It means handling CSRF, but it's the safer default for production.

4. Keep secrets in the environment

The Google client ID can be public (it ships in the frontend), but the JWT secret must stay in an environment variable on the server and never be committed to the repository.

Takeaway

Use Google to answer one question, "who is this?", then hand the user your own JWT so the rest of your API stays simple and provider-agnostic. Verify ID tokens, link only verified emails, and store tokens carefully, and you get the convenience of social login without giving up control.

The Real Estate Marketplace project page has the live demo and source code.