Google OAuth

Authenticate users with Google OAuth using Passport.js and JWT for secure, scalable Express backends.

authoauthgooglepassportexpressjwtsecurity
v2.0.0auth

Overview

A developer-ready Google OAuth 2.0 authentication component built with Passport.js and JWT. It provides secure OAuth login with automatic JWT issuance and user profile management. Perfect for adding Google-based authentication to any Express or Next.js app.

Installation

CLI
npx backternity add auth-oauth-google

What This Does

Installs Passport.js-based Google OAuth flow with JWT token handling and Express integration.

Files & Folders Created

File / PathDescription
/src/config/passport.jsConfigures Passport Google OAuth 2.0 strategy.
/src/routes/auth.jsRoutes for /auth/google and /auth/google/callback.
/src/services/userService.jsHandles user creation and retrieval.
/.env.exampleExample environment configuration for OAuth and JWT.

Files to be modified

File / PathDescription
server.jsMounts /auth routes and configures Passport middleware.
frontend/.envAdd FRONTEND_URL for redirect handling.

Configuration

# Google OAuth Configuration
GOOGLE_CLIENT_ID=your-google-client-id.apps.googleusercontent.com
GOOGLE_CLIENT_SECRET=your-google-client-secret

# JWT Configuration
JWT_SECRET=your-super-secret-key
JWT_EXPIRES_IN=7d

# Application URLs
BACKEND_URL=http://localhost:3001
FRONTEND_URL=http://localhost:3000

Frontend Integration

Use the endpoints below to implement secure Google login from your Next.js frontend. The backend returns a signed JWT and user profile after successful authentication.

GET/auth/google

Redirects the user to Google for OAuth authorization.

GET/auth/google/callback

Handles Google's callback, issues JWT, and redirects the user to the frontend with the token.

Example

1// app/components/GoogleLogin.jsx 2'use client'; 3import { useState, useEffect } from 'react'; 4 5export default function GoogleLogin() { 6 const [user, setUser] = useState(null); 7 const [message, setMessage] = useState(''); 8 9 useEffect(() => { 10 // Capture token from callback redirect 11 const params = new URLSearchParams(window.location.search); 12 const token = params.get('token'); 13 if (token) { 14 localStorage.setItem('accessToken', token); 15 fetchUser(token); 16 } 17 }, []); 18 19 async function fetchUser(token) { 20 try { 21 const res = await fetch('/api/auth/me', { 22 headers: { Authorization: 'Bearer ' + token }, 23 }); 24 const data = await res.json(); 25 setUser(data.user); 26 } catch { 27 setMessage('Failed to fetch user profile.'); 28 } 29 } 30 31 return ( 32 <div className="max-w-sm mx-auto bg-black/20 border border-white/10 rounded-xl p-6 text-white space-y-4"> 33 <h2 className="text-xl font-semibold">Login with Google</h2> 34 35 {!user && ( 36 <button 37 onClick={() => (window.location.href = 'http://localhost:3001/auth/google')} 38 className="w-full bg-blue-500 hover:bg-blue-600 text-white font-semibold py-2 rounded-md transition-colors" 39 > 40 Continue with Google 41 </button> 42 )} 43 44 {user && ( 45 <div className="p-3 bg-emerald-500/10 rounded-lg border border-emerald-500/20"> 46 <p className="text-sm text-emerald-300">Logged in as {user.name}</p> 47 <p className="text-xs text-white/70 mt-1">{user.email}</p> 48 <p className="text-xs text-white/70 mt-1">Provider: Google</p> 49 </div> 50 )} 51 52 {message && <p className="text-amber-400 text-sm">{message}</p>} 53 </div> 54 ); 55}

Usage

1// Example protected route using JWT 2const jwt = require('jsonwebtoken'); 3 4function verifyToken(req, res, next) { 5 const token = req.headers.authorization?.replace('Bearer ', ''); 6 if (!token) return res.status(401).json({ error: 'No token provided' }); 7 try { 8 req.user = jwt.verify(token, process.env.JWT_SECRET); 9 next(); 10 } catch { 11 res.status(401).json({ error: 'Invalid token' }); 12 } 13} 14 15app.get('/api/me', verifyToken, (req, res) => { 16 res.json({ message: 'Authenticated user', user: req.user }); 17});

Get in Touch

For partnerships, collaborations, or custom backend components - let’s build something powerful together.

Send us a message

Reach us directly

Email

team@backternity.dev

Quick Answers

Are components free?

Yes, they’re absolutely free to use.

Do you offer custom work?

Absolutely, we build scalable backend systems tailored to your stack.

How often are updates released?

Monthly, with new components, optimizations, and features.

Google OAuth – Auth Component | Backternity