Smart GeekSmart Geek
HomeArticlesCategories
Smart Geek

Thoughtful articles on technology, design, and culture in multiple languages.

Navigation

  • Home
  • Articles
  • Categories
  • About
  • Contact
  • Privacy Policy
  • RSS Feed

© 2026 Smart Geek. All rights reserved.

BlogProgrammingHow to Add Login with Google to Your Website
Programming

How to Add Login with Google to Your Website

Adding "Login with Google" to your site used to mean wading through pages of confusing OAuth documentation just to get a single button working. In 2026, the actual implementation takes under an hour once you know the exact order of steps and this guide walks you through every single one, with the real code you'll actually paste into your project.

Sayed Bin FahadSayed Bin Fahad
July 17, 202613 min read66 views
how to implement login with googlegoogle oauth login tutorialgoogle sign-in integration guideadd google login to website 2026google oauth 2.0 setupauth

Adding "Login with Google" to your site used to mean wading through pages of confusing OAuth documentation just to get a single button working. In 2026, the actual implementation takes under an hour once you know the exact order of steps and this guide walks you through every single one, with the real code you'll actually paste into your project.


What Is "Login with Google" and How Does It Work?

"Login with Google" lets users sign into your website using their existing Google account instead of creating and remembering a new password, and it works using the OAuth 2.0 authorization framework behind the scenes. If you've read our guide on API authentication methods, you already know OAuth 2.0 is the protocol powering every "Login with X" button. Google's implementation follows that same pattern, just with Google acting as the identity provider. When a user clicks the button, Google verifies who they are, asks for consent to share specific profile details (like name and email), and hands your app back a signed token you can trust without ever seeing their password.


Step 1: How Do You Create a Project in Google Cloud Console?

Creating a project is the first thing you do, and it's what houses every credential you'll generate later. Go to console.cloud.google.com, sign in with any Google account, click the project dropdown at the top of the page, and select New Project. Give it a recognizable name something like "MySite Login" and click Create. Google Cloud projects are free to create, and one project can hold credentials for multiple apps if needed.


Step 2: How Do You Set Up the OAuth Consent Screen?

The OAuth consent screen is the permission prompt Google shows users before they log in, and you configure it before you can generate any credentials. In the Cloud Console, navigate to what Google now often labels the Google Auth Platform setup (this area was previously called the "OAuth consent screen," and you may still see that name depending on your console version). You'll fill in your app name, a support email, and optionally a logo. Choose External as the user type unless you're building something strictly for an internal Google Workspace organization, then add the scopes you need for basic login, email and profile are enough.


Step 3: How Do You Get Your Client ID and Client Secret?

Your Client ID and Client Secret are generated together when you create OAuth 2.0 credentials, and both live in the Clients section of the Cloud Console (sometimes still labeled "Credentials" on older console versions). Click Create Credentials → OAuth Client ID, choose Web application as the type, and Google immediately generates both values. The Client ID looks something like 847293651042-a8f7g2h9j3k1.apps.googleusercontent.com and is safe to use in frontend code. The Client Secret is not, it's meant strictly for server-side use if you're exchanging authorization codes directly, and for a standard Sign-In button setup like this one, you often won't even need to use it in your code, but Google generates it regardless.

⚠️ Never Expose Your Client Secret in Frontend Code The Client Secret should never appear in any JavaScript file a browser can download, any public GitHub repository, or any client-side environment variable. Treat it exactly like a password. If you're only implementing a basic Sign-In button (not exchanging authorization codes server-side), you likely won't need to reference the secret in your code at all but store it securely in your backend environment variables regardless, since Google ties it permanently to your Client ID.


Step 4: How Do You Add Authorized Redirect URIs?

Authorized redirect URIs (and the closely related Authorized JavaScript origins) are the exact URLs you register with Google as allowed destinations for the sign-in response. Anything not on this list gets rejected. On the same credentials screen from Step 3, scroll to Authorized JavaScript origins and add your site's domain (e.g., https://yoursite.com), then add Authorized redirect URIs if you're using a server-side redirect flow (e.g., https://yoursite.com/auth/callback). For the button-based flow this guide uses, the JavaScript origin matters most. Save your changes before moving on there's a dedicated section further down that covers exactly why mismatches here are the single most common setup error beginners hit.


Step 5: How Do You Install the Google Identity Services Library?

Installing the Google Identity Services (GIS) library means adding one script tag to your HTML. No npm install, no build step required for a basic implementation. Place this in the <head> of any page where a user might sign in:

html

<script src="https://accounts.google.com/gsi/client" async defer></script>

Loading it with async keeps it from blocking your page's rendering while it fetches in the background.


Step 6: How Do You Add a "Sign in with Google" Button to Your Page?

Adding the button itself just requires two small <div> elements with specific data attributes that the GIS library reads automatically once it loads. Drop this into your HTML wherever you want the button to appear:

html

<!-- Configuration for the sign-in flow -->
<div id="g_id_onload"
     data-client_id="YOUR_CLIENT_ID.apps.googleusercontent.com"
     data-callback="handleCredentialResponse"
     data-auto_prompt="false">
</div>

<!-- The visible button -->
<div class="g_id_signin"
     data-type="standard"
     data-size="large"
     data-theme="outline"
     data-text="sign_in_with"
     data-shape="rectangular"
     data-logo_alignment="left">
</div>

Replace YOUR_CLIENT_ID with the actual Client ID from Step 3. The data-callback attribute tells Google which JavaScript function to call once a user successfully signs in. You'll define that function in the next step.


Step 7: How Do You Handle the Returned Credential on the Frontend?

Handling the returned credential means writing the handleCredentialResponse function that Google calls automatically after a successful login, and forwarding that token to your backend for real verification. The token Google sends back is a JWT, the same three-part structure (header, payload, signature) covered in our API authentication guide.


Learn about: Fetch API in Javascript


javascript

function handleCredentialResponse(response) {
  // response.credential is a JWT (ID token) issued by Google
  const idToken = response.credential;

  // Send the token to your backend - never trust it on the frontend alone
  fetch('/api/auth/google', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ token: idToken })
  })
    .then(res => res.json())
    .then(data => {
      console.log('Backend confirmed login:', data);
      // Redirect or update your UI here
    })
    .catch(error => console.error('Login failed:', error));
}

Notice this function only forwards the token. It doesn't make any authentication decisions itself. That distinction matters, and it's exactly what the next step handles properly.


Step 8: How Do You Verify the Token on Your Backend?

Verifying the token server-side is the step that actually confirms the login is legitimate, and skipping it means trusting data a browser could have tampered with. Install Google's official library and use its built-in verification function:

bash

npm install google-auth-library

javascript

const { OAuth2Client } = require('google-auth-library');
const client = new OAuth2Client();

const CLIENT_ID = process.env.GOOGLE_CLIENT_ID;

async function verifyGoogleToken(idToken) {
  const ticket = await client.verifyIdToken({
    idToken: idToken,
    audience: CLIENT_ID
  });

  const payload = ticket.getPayload();

  // payload.sub is the permanent, unique Google user ID use this as your primary key
  return {
    userId: payload['sub'],
    email: payload['email'],
    name: payload['name']
  };
}

// Example Express route
app.post('/api/auth/google', async (req, res) => {
  try {
    const { token } = req.body;
    const user = await verifyGoogleToken(token);
    // Look up or create this user in your database, then start a session
    res.json({ success: true, user });
  } catch (error) {
    res.status(401).json({ success: false, error: 'Invalid token' });
  }
});

verifyIdToken() checks the token's cryptographic signature, confirms it was issued for your specific Client ID, and rejects anything expired or tampered with, all in one call.


What Does Each Setup Step Involve at a Glance?

Step

What You Do

Where

Common Error

1. Create Project

Set up a project to hold your credentials

Google Cloud Console

Creating credentials under the wrong active project

2. Consent Screen

Configure app name, support email, and scopes

Google Cloud Console

Leaving the app stuck in "Testing" mode after launch

3. Client ID & Secret

Generate OAuth 2.0 web application credentials

Google Cloud Console

Pasting the Client Secret into frontend code

4. Redirect URIs

Register every domain allowed to receive responses

Google Cloud Console

"Error 400: redirect_uri_mismatch"

5. Install GIS Library

Add the Google script tag to your page

Your Code (HTML)

Script blocked by an existing Content Security Policy

6. Add Button

Insert the Sign-In button markup

Your Code (HTML)

Button fails to render due to a missing Client ID

7. Handle Credential

Capture the JWT and forward it to your backend

Your Code (JavaScript)

Trusting the token without backend verification

8. Verify Token

Confirm authenticity server-side

Your Code (Node.js)

Wrong audience value passed to verifyIdToken


What Are Authorized Redirect URIs and Why Do They Matter?

Authorized redirect URIs matter because Google will flatly refuse to complete a sign-in for any URL that isn't registered exactly as typed. No partial matches, no assumptions. This trips up more beginners than any other step in the entire process. The match has to be character-for-character: https://yoursite.com and https://www.yoursite.com are considered two completely different origins, and a trailing slash difference is enough to trigger a rejection. I've lost a full afternoon to a redirect mismatch that turned out to be nothing more than an extra slash at the end of a URL. Copy these values directly rather than retyping them.

The distinction worth understanding: Authorized JavaScript origins cover the domain-level access needed for the button/One Tap flow used in this guide, while Authorized redirect URIs specifically matter if you implement a full server-side redirect flow instead. Most beginner implementations using the GIS button only need the JavaScript origins configured correctly.


How Do You Test Google Login Locally Before Going Live?

Testing locally means adding your local development address. Typically something like http://localhost:3000 to the Authorized JavaScript origins list in the Cloud Console, so Google treats your local machine as a valid, trusted origin. One detail worth knowing: for Cloud projects created before April 28, 2025, localhost was enabled automatically; for anything created after that date, you need to add it manually before local testing will work. While you're still developing, keep your OAuth consent screen in Testing mode and add your own Google account (and any teammates') as designated test users. This lets you sign in without needing to complete Google's full app verification process first, which you only need before a public launch.


What Are the Most Common Google Login Setup Mistakes?

Why Does a Mismatched Redirect URI Break Login?

A mismatched redirect URI breaks login because Google checks the requested URL against your registered list with exact, literal string matching. Any difference in protocol, subdomain, port, or trailing slash causes an immediate rejection. This produces the well-known "Error 400: redirect_uri_mismatch" screen, and the fix is almost always copying the exact URL from your browser's address bar directly into the Cloud Console field.

What Happens If You Forget to Publish the OAuth Consent Screen?

Forgetting to publish your consent screen means only manually added test users can log in, while everyone else sees an "app not verified" block screen. Testing mode is meant for development, and it caps you at a small number of test users. Before a real launch, you need to move the consent screen to Production status, which may require Google's verification review if you're requesting more than basic profile and email scopes.

Why Is Exposing the Client Secret in Frontend Code Dangerous?

Exposing the Client Secret in frontend code is dangerous because anyone who views your page source or intercepts a network request gains a credential that can impersonate your app when requesting tokens from Google. Unlike the Client ID, which is designed to be public, the Client Secret is meant exclusively for trusted server environments. Treat any accidental exposure as an immediate signal to regenerate it in the Cloud Console.

What Goes Wrong When You Don't Handle Token Expiry?

Not handling token expiry means your app eventually starts rejecting valid users with confusing errors once their session token ages out, typically after about an hour for Google ID tokens. Build your backend session logic to detect an expired or invalid token gracefully and redirect the user back to the Sign-In button rather than showing a raw error message.


FAQ

Is Google Login Free to Implement?

Yes, Google does not charge anything to implement Sign-In with Google, regardless of how many users authenticate through it. The only costs you might incur are related to your own infrastructure (hosting, backend servers), not to Google's authentication service itself.

Do I Need a Verified Domain?

Not for development or small-scale testing. Testing mode with manually added test users works without any verification. You only need to complete Google's OAuth app verification and domain ownership process (through Google Search Console) if you're launching publicly and requesting sensitive scopes beyond basic profile and email, or if you want to remove the "unverified app" warning for all users rather than just test accounts.

Can I Use Google Login Without a Backend?

Technically yes, for cosmetic purposes only, you can decode the returned JWT directly in the browser to display a user's name or email without ever touching a server. This is not secure for anything that matters, though, since a modified frontend could fake the entire flow. Any real authentication decision creating a session, granting access to protected data. It needs backend verification of the token's signature, as shown in Step 8.

What Happens If a User Revokes Access?

If a user revokes your app's access through their Google Account settings, any tokens your app was relying on become invalid immediately, and the next login attempt or API call will fail. Your app should handle this gracefully by catching the failed verification and simply prompting the user to sign in again, rather than crashing or showing a raw error.

Does Google Login Work for Mobile Apps Too?

Yes, Google provides dedicated SDKs for native mobile implementation, including the Credential Manager API on Android and a corresponding Sign-In library for iOS. These follow the same underlying OAuth 2.0 concepts covered in this guide but use a different Client ID type (Android or iOS instead of Web) created within the same Google Cloud project.


Ready to Launch Google Login on Your Own Site?

Every piece of this setup from the console configuration, the button markup, and the two-step verification between frontend and backend follows the same pattern regardless of how big or small your project is. Work through the eight steps in order, test locally with a registered localhost origin before you worry about production verification, and you'll have a working, secure login button running well within the hour this guide promised.

Sayed Bin Fahad

Sayed Bin Fahad

Contents

  • What Is "Login with Google" and How Does It Work?
  • Step 1: How Do You Create a Project in Google Cloud Console?
  • Step 2: How Do You Set Up the OAuth Consent Screen?
  • Step 3: How Do You Get Your Client ID and Client Secret?
  • Step 4: How Do You Add Authorized Redirect URIs?
  • Step 5: How Do You Install the Google Identity Services Library?
  • Step 6: How Do You Add a "Sign in with Google" Button to Your Page?
  • Step 7: How Do You Handle the Returned Credential on the Frontend?
  • Step 8: How Do You Verify the Token on Your Backend?
  • What Does Each Setup Step Involve at a Glance?
  • What Are Authorized Redirect URIs and Why Do They Matter?
  • How Do You Test Google Login Locally Before Going Live?
  • What Are the Most Common Google Login Setup Mistakes?
  • Why Does a Mismatched Redirect URI Break Login?
  • What Happens If You Forget to Publish the OAuth Consent Screen?
  • Why Is Exposing the Client Secret in Frontend Code Dangerous?
  • What Goes Wrong When You Don't Handle Token Expiry?
  • FAQ
  • Is Google Login Free to Implement?
  • Do I Need a Verified Domain?
  • Can I Use Google Login Without a Backend?
  • What Happens If a User Revokes Access?
  • Does Google Login Work for Mobile Apps Too?
  • Ready to Launch Google Login on Your Own Site?

Tags

Programming

Related Articles

Fix 'MySQL Shutdown Unexpectedly' in XAMPP
Programming

Fix 'MySQL Shutdown Unexpectedly' in XAMPP

Fix the frustrating “MySQL Shutdown Unexpectedly” error in XAMPP with this clear, step-by-step guide. Learn the most common causes from port conflicts to corrupted data files and follow simple solutions to get your local server running smoothly again in minutes.

mysqlxamppphp
Sayed Bin Fahad
Apr 9, 2026 5 min
How to Install Python on Windows 11
Programming

How to Install Python on Windows 11

Learn how to install Python on Windows 11 step-by-step. Covers download, PATH setup, version check, and common errors. Updated May 2026 for beginners.

pythonwindows 11install python
Sayed Bin Fahad
May 3, 2026 9 min
Programming

Python vs JavaScript: Which Should You Learn First?

You've decided to finally learn programming, and now you're stuck on the first decision that feels way bigger than it should Python or JavaScript? I've watched dozens of beginners freeze at this exact crossroads, so let's settle it with facts instead of hype.

javascriptpythonweb
Sayed Bin Fahad
Jun 18, 2026 8 min