DEV Community

Cover image for A Beginner's Guide to Implementing One-Click Social Authentication with Node.js and HTML
Diane Mahusay for UP Mindanao SPARCS

Posted on

A Beginner's Guide to Implementing One-Click Social Authentication with Node.js and HTML

This article was co-authored with Jed Somera

Introduction:

The debate between a developer and a UI designer is like a fight between a heavy padlock and a sliding door. The developer wants a 10-step login process because they believe more hurdles make the house safer from hackers. To them, every extra password or code is a brick in a strong wall. On the other hand, the designer wants a "one-click" button to get the user inside as fast as possible without getting frustrated. The designer fears that if the door is too hard to open, the user will just give up and leave. It’s a constant battle to find a balance where the door is safe enough to keep bad people out, but easy enough that the owner doesn't hate using it.

So, we compiled a detailed beginner’s guide and tutorial on implementing one-click auth to satisfy both developers and UI designers.


Table of Contents:


What is Social Auth?

Social authentication lets users log into websites using their existing social media accounts instead of creating new credentials from scratch. Think about creating an account on social media (like Pinterest and YouTube) using Google because you are too lazy to create an account, or the process of creating one is too long. Tapping "Sign in with Google" is essentially telling the new app to use your existing Google identity. Google confirms who you are, and you're instantly logged in and ready to scroll.

alt text

The benefits extend beyond sign-up. Users no longer need to remember multiple passwords, reducing password fatigue, while simplifying account recovery and providing consistent experiences across devices.


Why use Social Auth?

Social authentication is a universal digital keycard, letting you access multiple sites without creating unique, vulnerable passwords for each. Instead of storing your password (your "key"), a website asks a trusted provider, like Google or Apple, to verify your identity. You log in privately with the provider, which then gives the website a temporary pass confirming your permission to enter. Instead of building complex security systems, developers implement an OAuth 2.0 flow. You log in privately with the provider, which then gives the website a temporary pass confirming your permission to enter.

The OAuth 2.0 flow is the modern industry standard for secure inter-website communication. It works by giving a requesting website a temporary "digital keycard" instead of your master password. This OAuth service ensures the website only accesses approved data (like your profile or email) and never sees your actual password.


What are JWTs?

Think of JWT (JSON Web Token) like a passport. Instead of the immigration officer checking a big list of names (database) at who’s valid to fly every time you want to go abroad, they just look at your passport. If the passport is verified (the signature), you are granted access to fly.

How Does It Work?

When you want to log in, there are two important things to keep in mind: Authentication and Authorization. Authentication is the process of verifying who you are using your credentials. Authorization is checking what you’re allowed to do using a token. This is where JWT shines. A JWT consists of three parts:

  1. Header: This contains the metadata about the type of token and the algorithm used to make the token.
  2. Payload: This contains the data itself, including the User ID, name, expiration date, etc. It is important to note that JWTs are encoded/hashed, not encrypted. Like a passport, anyone can read them, so never put sensitive data like passwords inside.
  3. Signature: This is the “security seal”. The server uses a secret key to sign the token. This mechanism ensures that the payload can be trusted. The server takes a secret value, uses the header and payload, hash it, and combines it with the two previous parts.

What does this achieve?

  1. The Server Does Not Have to “Remember” You (Stateless) Traditionally, a dedicated server called sessions had to keep a giant list of every person logged in. If your system has a million people logged in, the server would not handle it efficiently and lead to slow response times. With JWT, the server doesn’t have to store anything. It just looks at your “passport”, verifies the passport, and grants you access. This makes the app faster and easier to scale.
  2. It is Impossible to Fake Using JWT, the token is locked with a “Secret Key” that only the server knows. If an attacker changes even one letter in the token,
  3. It is Lightning Fast Traditionally, a database would be needed to authorize a user. Using hashing to verify a signature is faster. Since the check happens in milliseconds, the user doesn’t see long loading screens. Everything is snappy and smooth. Additionally, due to its “Self-Contained” nature, it doesn’t just say “I am user #1”; It includes the user’s ID, Roles, Authorization Level, and expiration date directly in its form. Because of this, the system doesn’t need to cross-check with the server every time it’s used.
  4. Eliminates the “It works on my device.” Whether you are on a phone, a laptop, or a tablet, the “passport” works the same way. It does not rely on old-school browser strategies like cookies. It also works identically whether your backend is written in Node.js or Python, and whether your client is a web browser, a mobile app, or an IoT device.

Tech Stack Overview

To build this one-click experience without taking shortcuts, we are using a lightweight and transparent stack that lets us control every part of the it.

Tech Usage
Node.js Serves as the backend runtime for handling server-side logic and API requests.
Express.js Manages web routing and creates the callback endpoints for the authentication flow.
Passport.js Middleware for Node.js that simplifies authentication by providing a standardized "Strategy" system to handle complex login processes.
HTML/CSS Defines the structure and styling of the login interface to meet UI/UX standards.
Dotenv Secures the application by storing sensitive API keys and secrets in environment variables.
OAuth 2.0 The standard protocol used to securely handshake with providers like Google or GitHub.

HTML (HyperText Markup Language) is a fundamental "skeleton" of any website. Running directly within a user's web browser (such as Chrome, Safari, or Firefox), this code instructs the browser precisely what elements to display. Similar to a restaurant menu, HTML clearly defines the content's structure, signaling items like "This is a heading," "This is a paragraph," and "This is a button."

While Node.js is the server-side "engine" that powers your application, distinct from the HTML the user sees in their browser. Think of Node.js as the "Chef" working behind the scenes. This runtime environment enables developers to use JavaScript for crucial server-side operations, such as interacting with databases and communicating with external APIs, performing all the heavy lifting.

If Node.js is the “chef” itself, Express.js is the manager who makes sure everything runs smoothly. Without a manager, customers wouldn't know where to sit or how to order. It is in charge of the Routing and Middleware. When a user types http://localhost:3000/auth/google, Express is the host that directs people to the right "rooms" in your code. Additionally, it uses “Middleware” to pass data through different steps–like checking your .env secrets or verifying a token–before finishing the request,t just like “garnishing” a food before it reaches the customer.

Lastly, Passport.js is your professional “Identity Expert”. Instead of you manually handling the back-and-forth paperwork with Google, Passport takes over and manages the entire security handshake for you. It uses specialized "Strategies" to recognize different types of logins, acting like a bouncer who is specifically trained to verify Google IDs. Through this, you can keep your code clean and focus on building your app while a specialist guards the front door.


Pre-requisite

For this guide, we’ll be using Windows (Command Prompt/PowerShell).

  1. Download Node.js. Go to (https://nodejs.org/en/download), select your device, and click Download. Node/js Website
  2. Run the Installation. Open the downloaded file and follow the installation wizard. For most users, the default settings are perfect.
  3. Verify the Installation. Once the installer finishes, you need to make sure your computer sees Node.js. Put this in your Command Prompt:
node -v
npm -v
Enter fullscreen mode Exit fullscreen mode

OAuth Service

The OAuth service acts as a digital middleman, helping two different websites communicate securely. Instead of you giving a new website your actual Google password, the OAuth service steps in to handle a trusted introduction. When you click "Sign in with Google," you are temporarily leaving the new website to sign in directly to Google’s secure servers. Google confirms who you are and asks if you're okay with sharing basic details, like your name or email, with that specific site.

The Client ID and Client Secret act as a digital ID for your website. The Client ID is the public username; it tells Google which app is requesting a "trusted introduction," allowing Google to display the correct name and logo on the sign-in screen. Since it's public, the Client ID can safely be included in your code or "Sign in with Google" button link.

The Client Secret is your website's private password, known only to Google and your server. Your server uses this secret to prove its identity to Google after a user grants login permission. You must keep it hidden and never share it or post it online. If compromised, a third party could impersonate your site and steal user "digital passes."

Here are the steps to get your Client ID and Client Secret:

  • Choose an OAuth Provider There are several kinds of providers you can use. You can search platforms like Meta, Microsoft, or even GitHub to find what interests you.

alt text

We’ll be using Google Cloud Console

  • Create your Client ID and Client Secret

Step 1: Create a New Project
On the upper left corner, click “Select a project’

OAuth

A pop-up will appear with your previous projects, BUT click “New project.”

OAuth

After clicking the New Project, it will direct you to this. Under Name, give your project an appropriate name. Then Click “Create.”

OAuth

Step 2: Create your credentials

Once the project is created, select it, and a Dashboard will be shown. In the center, API’s is there, click the “Go to APIs overview.”

OAuth

Find the credentials on the left side and select them for you to create your Client ID and Client Secret.

OAuth

In the upper corner, you’ll see “Create credentials”, then choose
“OAuth client ID.”

OAuth

If you see an alert to configure consent screen, click it. It will direct you to the Branding tab, then select “Get Started”. It will lead you to this tab.

Name the app that you’ll be going to do (in our case is Social-Auth). Fill up all the necessary info, then click “Create.”

OAuth

Step 3: Create your own OAuth Client
After you click Create, you will now see the button “Create OAuth Client”. Click it, and set the application type to “Web Application”.

OAuth

Crucial Step: add (http://localhost:3000/auth/google/callback) under the Authorized redirect URls. (Reminder: This is not what everyone uses, but since we are following through the tutorial, that’s the URL/port we are going to use)

A pop-up with the Client ID and Client Secret will be shown. Download the JSON file for easy viewing of the information.

OAuth

Once you click DONE, the new Client ID will be added to the list. You can edit/delete the name or add URLs going forward.


Why does a callback matter?

As you noticed, in the Authorized redirected URLs, we added a localhost callback link. That’s because when the user clicks “Sign in with Google”, it will redirect the user to Google’s secure login page. After the user enters their credentials and clicks "Allow," Google needs to know exactly where to send that user (and their secret authorization code) back to.

So, without adding the callback to the Authorized redirected URLs, the social auth will not happen.


Building a simple “Sign in with Google” Using HTML

In an OAuth 2.0 flow, the HTML button isn't just a UI element; it is a trigger. When a user clicks it, they are essentially saying, "I trust this application to talk to Google on my behalf." Without this button, there is no way for the user to initiate the secure redirection to the provider.

  • Create an HTML file. In your Visual Studio Code (VS Code), first create a folder. You will store all your files there. Then, create a new file, name it index.html

VS Code


Building the backend of a simple “Sign in with Google.”

Since the frontend is ready for testing, let us make the logic that works behind the UI/UX.

Folder Structure:

social-auth/
├── public/             <-- Frontend (UI/UX)
│   └── index.html      
├── .env                <-- Security (Secrets)
├── server.js           <-- Backend (Logic & JWT)
├── .gitignore          <-- Git Safety
└── package.json        <-- Dependencies

Enter fullscreen mode Exit fullscreen mode

Step 1: Environment Setup

Create your Project folder:

  • Windows: Right-click on your Desktop > New > Folder. Name it social-auth.
  • Mac/Linux: Right-click on your Desktop > New Folder (or use the shortcut Shift + Cmd + N). Name it social-auth.\

Open in VS Code

  • Open Visual Studio Code.
  • Go to File > Open Folder (or Open on Mac) and select your social-auth folder.

Folder

Open the VS Code Terminal

  • Go to the top menu and select Terminal > New Terminal. Tip: You can also use the shortcut Ctrl + shift + ~(backtick) on Windows/Linux or Cmd + ` on Mac.
  • You should see a cursor blinking at the bottom of your screen. This is where we will type our commands.

VS

VS

Initialize the project

  • Type the following in the VS Code terminal and hit Enter:

npm init -y

This creates a package.json file, which is essentially a "shopping list" of all the tools your project needs.

VS

Install dependencies via VSCode Terminal

npm install express passport passport-google-oauth20 jsonwebtoken dotenv

Wait for the progress bar to finish. This downloads the code for the security and networking features we need.

VS

Create the necessary files

  • Inside VS Code, click the New File icon (next to the folder name in the sidebar) and create:
  • server.js: Your backend "brain."
  • .env: Your secret vault (be careful: the filename starts with a dot!).
  • A folder named public/: Right-click the sidebar to create a folder. Inside it, create index.html and paste your partner's design code.

VS


Server.js

The backend is split into three main logic blocks:

  • Authentication (Google Passport): We use the GoogleStrategy to let Google verify the user. We don't need to handle passwords ourselves—Google does the heavy lifting, which is safer for the user and easier for us.
  • Networking (The Callback): The callbackURL acts as a secure "Return Address." Google will only send the user back to this specific URL, preventing "Man-in-the-middle" attacks.
  • Authorization (JWT Generation): Once Google confirms the identity, we use jwt.sign() to issue a Stateless JWT.
  • The Signature: We combine the user's data with our JWT_SECRET to create a hash. If a user tries to change their ID in the token, the math will fail, and the "Bouncer" (server) will reject them.

Phase 2: Connecting to the UI (index.html)

The Button: In public/index.html, ensure your login button link looks like this:

<a href="/auth/google" class="btn-google">Sign in with Google</a>

The Result: When the process finishes, the backend will display the JWT string on the screen, proving the handshake was successful.

Phase 3: Testing

  1. Start the Server: In your VS Code Terminal, type:

node server.js

  1. Visit Your Site: Open your browser and go to http://localhost:3000.
  2. Log In: Click the "Sign in with Google" button. If everything is correct, Google will verify you, and you'll see your JWT string!

Conclusion: Why This Matters

By completing this tutorial, you’ve built more than just a login button—you’ve implemented a modern architecture that balances security, scalability, and user experience.

The Purpose of Google Social-Auth

In this project, Google acts as our Identity Provider. Using an established giant like Google is a massive win for cybersecurity. It means we don't have to worry about storing and hashing passwords ourselves—a task that, if done wrong, could lead to massive data breaches. We "outsource" the most dangerous part of security to experts, ensuring our users' data is protected by world-class infrastructure.

The Power of the JWT

Once Google confirms who the user is, our backend issues a JSON Web Token (JWT). This is the heart of Stateless Authorization. Unlike traditional systems that force the server to remember every single logged-in user (which slows down the site as it grows), the JWT allows the server to verify a user's identity instantly using just math. It is lightweight, secure, and built for the modern web.

The Vital Role of UI/UX

Security is useless if the interface is too confusing to use. The frontend design we integrated isn't just "eye candy"; it is a tool for Trust. By using recognizable branding and a smooth one-click flow, we reduce "User Friction." A high-quality UI/UX ensures that the complex cybersecurity handshake happening in the background remains invisible, providing a seamless experience that makes the user feel both safe and empowered.

Congratulations! You’ve just built a secure, modern social-auth system using OAuth and JWT.


References:

Top comments (0)