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
- Key on
sub, never on email alone: Users can change their Google Workspace email address, while Google'ssubidentifier stays permanent. - Check
email_verified === true: Before auto-linking a Google login to an existing password account with the same email, confirmemail_verifiedis strictly booleantruein Google's signed ID token. - Never ship
GOOGLE_CLIENT_SECRETinVITE_*variables: AnyVITE_orREACT_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 whenevercredentials: "include"is active. Return the exact allowed origin plusAccess-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/meonce withcredentials: "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.comaccounts 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-changingPOST/PATCH/DELETEroutes. - 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.