HomeBlogHow to Integrate Google OAuth Login...

Engineering Guide · 8 min read · November 9, 2026

How to Integrate Google OAuth Login into a React Application

Drop-in Google login tutorials often leave React apps storing long-lived tokens in localStorage or trusting unverified client claims. A production-ready implementation pairs Google Identity Services with backend authorization-code exchange, HttpOnly session cookies, and strict email-verified account matching.

Author
Smit Desai
Published
November 9, 2026
Read time
8 min read
Topic
APIs & Integrations
Services
Custom Web · Mobile Apps · All Services

Adding a "Continue with Google" button to a React app takes twenty minutes if you follow a snippet. Making it survive real security audits, mobile in-app browsers, account linking edge cases, and session expiry without logging users out mid-form takes much more care.

Most fragile React auth setups fail in the exact same spot: they either trust raw user profile objects posted from the browser or stuff access tokens into localStorage, turning a minor frontend XSS bug into full account takeover.

Choosing the Right OAuth 2.0 Flow for React

Forget the legacy Implicit Flow (response_type=token)—it leaks tokens in URL fragments and is deprecated in modern OAuth best practices. For a React SPA paired with your own backend API (Laravel, Node, Go, or Next.js Route Handlers), pick between two clean patterns:

Flow Pattern How It Works Best For Key Gotcha
GIS Authorization Code Popup React triggers Google popup, receives one-time code, sends code to your backend SaaS dashboards wanting zero page reload Popups can be blocked in Instagram/LinkedIn in-app browsers
Full-Page Redirect + PKCE Browser redirects to Google, returns to /auth/callback, backend exchanges code + code_verifier Mobile web, strict corporate browsers, multi-tenant SSO Must persist state and code_verifier cleanly across redirect

Both flows share one non-negotiable rule: your backend—not React—validates the Google credential and issues your application session.

Frontend Integration with Google Identity Services

Using @react-oauth/google (a thin React wrapper around Google Identity Services) with flow: "auth-code" keeps client secrets off the browser and hands your backend a short-lived authorization code:

import { GoogleOAuthProvider, useGoogleLogin } from "@react-oauth/google";

function GoogleSignInButton() {
  const login = useGoogleLogin({
    flow: "auth-code",
    onSuccess: async ({ code }) => {
      const res = await fetch(`${import.meta.env.VITE_API_URL}/auth/google/callback`, {
        method: "POST",
        credentials: "include", // Required so backend can set HttpOnly cookies
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ code }),
      });

      if (!res.ok) {
        throw new Error("Google authentication failed");
      }

      window.location.assign("/dashboard");
    },
    onError: () => {
      console.error("Google sign-in cancelled or blocked");
    },
  });

  return (
    <button type="button" onClick={() => login()}>
      Continue with Google
    </button>
  );
}

export function AppAuthShell({ children }: { children: React.ReactNode }) {
  return (
    <GoogleOAuthProvider clientId={import.meta.env.VITE_GOOGLE_CLIENT_ID}>
      {children}
    </GoogleOAuthProvider>
  );
}

Notice credentials: "include". Without it, browsers silently drop Set-Cookie headers when your React frontend runs on app.example.com and your API runs on api.example.com. Also verify that your Google Cloud Console OAuth client allows both your local origin (http://localhost:5173) and exact production origins under Authorized JavaScript origins and Authorized redirect URIs (postmessage for popup code flow).

Backend Code Exchange and Session Issuance

When /auth/google/callback receives code, your backend exchanges it directly with https://oauth2.googleapis.com/token using client_id, client_secret, and redirect_uri: "postmessage" (for GIS popup flow), then verifies the returned id_token signature, aud (your Client ID), iss, and exp.

Once verified, resist the urge to return a raw JWT in JSON for React to store in localStorage. Instead, set an HttpOnly; Secure; SameSite=Lax session cookie and maintain a clean user identity schema:

CREATE TABLE user_oauth_identities (
  id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  user_id BIGINT UNSIGNED NOT NULL,
  provider VARCHAR(32) NOT NULL,           -- 'google'
  provider_subject VARCHAR(255) NOT NULL,  -- immutable Google 'sub' claim
  email VARCHAR(255) NOT NULL,
  created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  UNIQUE KEY uniq_provider_subject (provider, provider_subject),
  INDEX idx_user_id (user_id)
);

Three Security Rules for Account Linking

  1. Key on sub, never on email alone: Users can change their Google Workspace email address, while Google's sub identifier stays permanent.
  2. Check email_verified === true: Before auto-linking a Google login to an existing password account with the same email, confirm email_verified is strictly boolean true in Google's signed ID token.
  3. Never ship GOOGLE_CLIENT_SECRET in VITE_* variables: Any VITE_ or REACT_APP_ environment variable is bundled straight into public JavaScript. Keep secrets exclusively on the API server, consistent with OWASP API Security guidelines.

Handling Cross-Origin Cookies, CORS, and Token Refresh

Local development and production deployments routinely trip over cookie rules between React SPAs and backend APIs:

  • CORS must specify exact origins: Access-Control-Allow-Origin: * is rejected by browsers whenever credentials: "include" is active. Return the exact allowed origin plus Access-Control-Allow-Credentials: true.
  • Keep sessions decoupled from Google's access token: Unless your app explicitly reads Google Calendar, Drive, or Gmail scopes on the user's behalf, you do not need to store Google refresh tokens at all. Authenticate once, issue your own rotating backend session, and let high-performance REST API endpoints enforce permissions.
  • Add an Auth Context bootstrap check: On initial React mount, call GET /api/me once with credentials: "include" to hydrate user state cleanly without flashing the login screen.

Testing Before Shipping to Production

Before pushing Google OAuth live, walk through four checks that catch 90% of launch-day tickets:

  • Consent screen status: Moving Google Cloud OAuth consent from Testing to In Production removes the 100-test-user limit (verification is only needed if you request sensitive/restricted scopes beyond openid email profile).
  • Workspace domain restrictions: Test both consumer @gmail.com accounts and custom Google Workspace domains if your SaaS targets B2B teams.
  • CSRF protection on cookie auth: Since your API now relies on cookies, enforce CSRF tokens or SameSite=Lax + custom header checks on state-changing POST/PATCH/DELETE routes.
  • Fallback for popup blockers: Detect popup failure cleanly and offer a standard redirect URI fallback on mobile browsers.

How SmitDev Builds Secure Authentication Systems

Auth bugs carry asymmetric risk: a small shortcut in OAuth state validation or cookie configuration becomes a headline vulnerability. Through custom web application development and full-stack architecture consulting—whether you are scaling in the US (hire developer USA), UK, Europe, UAE, Australia, or Singapore—I ship hardened React + API authentication layers, multi-tenant RBAC, and SSO integrations without fragile third-party lock-in.

Need a dedicated engineer to implement or audit your authentication stack? Book an hourly developer at $55/day for 8–9 hours of focused execution, explore our services, or engage $1,999/month ongoing delivery. Reach out via our contact page to review your auth architecture.

Written by Smit Desai · Principal Full-Stack & FDSE

8+ years shipping production systems · 171 case studies · 300+ WordPress servers managed for Finland partners.

Next Steps and Recommended Resources

Next Steps · Recommended Resources

Pillar 1 · Custom Web & SaaS

Custom Web Application Development

Production Laravel, Next.js, API, and multi-tenant SaaS systems engineered end to end at $55/day (8–9 hrs) or $1,999/mo.

Comparison · Buyer Guide

SmitDev vs Software Agencies

See side-by-side economics, senior code ownership, and onboarding speed vs traditional dev shops and marketplaces.

01 — Frequently asked questions

apis & integrations

Why should React apps avoid storing OAuth or JWT tokens in localStorage?

Any JavaScript running in the browser—including compromised third-party analytics scripts or an XSS vulnerability—can read localStorage. Issuing Secure, HttpOnly, SameSite cookies from your backend keeps session credentials inaccessible to client-side scripts.

Should I verify the Google ID token on the frontend or backend?

Always verify the token or exchange the authorization code on your backend server. Never trust user email, name, or sub claims posted directly from React, because an attacker can forge any JSON body sent to your API.

How do you link a Google login to an existing email/password account safely?

Match on the immutable Google sub claim first, and only match by email when email_verified is strictly true in Google's verified payload. Otherwise, an attacker could register an unverified email on another provider and hijack an existing user's account.

When should a React app use popup sign-in vs. full-page OAuth redirect?

Popup flows with Google Identity Services feel smoother inside single-page dashboards, while full-page Authorization Code + PKCE redirects are more resilient on mobile in-app browsers where popups get blocked.

03 — Have an engineering need?

hire the right expertise

Let's talk tech.

Deciding between an embedded forward deployed engineer or a senior full stack developer? Share your technical context and timeline.

Solitaire Corporate Park, Makarba, Ahmedabad, Gujarat 380015, India · IST (UTC+5:30) · --:-- IST · Mon–Fri 09:00–18:00 IST · US & EU overlap daily

No newsletter, no CRM. Just a reply.