Authentication is a critical part of modern web applications. OAuth is a secure and popular way to authenticate users via third-party providers like Google, GitHub, or Facebook. In this tutorial, we'll walk through setting up OAuth authentication using Node.js on the backend and React on the frontend.

🛠️ Tech Stack

  • Frontend: React (with Axios)

  • Backend: Node.js with Express

  • OAuth Provider: Google (though others like GitHub work similarly)

  • Passport.js: Middleware for authentication in Node.js


📦 Step 1: Set Up the Backend (Node.js + Express)

1. Initialize your project

mkdir oauth-node-react && cd oauth-node-react mkdir backend && cd backend npm init -y npm install express passport passport-google-oauth20 cookie-session dotenv cors

2. Configure your environment variables

Create a .env file:

GOOGLE_CLIENT_ID=your_google_client_id GOOGLE_CLIENT_SECRET=your_google_client_secret COOKIE_KEY=your_cookie_key

3. Set up the Express server

Create a file: index.js

const express = require('express'); const passport = require('passport'); const GoogleStrategy = require('passport-google-oauth20').Strategy; const cookieSession = require('cookie-session'); const cors = require('cors'); require('dotenv').config(); const app = express(); app.use(cors({ origin: 'http://localhost:3000', credentials: true })); app.use( cookieSession({ name: 'session', keys: [process.env.COOKIE_KEY], maxAge: 24 * 60 * 60 * 1000, // 1 day }) ); app.use(passport.initialize()); app.use(passport.session()); passport.serializeUser((user, done) => { done(null, user); }); passport.deserializeUser((obj, done) => { done(null, obj); }); passport.use( new GoogleStrategy( { clientID: process.env.GOOGLE_CLIENT_ID, clientSecret: process.env.GOOGLE_CLIENT_SECRET, callbackURL: '/auth/google/callback', }, (accessToken, refreshToken, profile, done) => { return done(null, profile); } ) ); app.get('/auth/google', passport.authenticate('google', { scope: ['profile', 'email'] }) ); app.get('/auth/google/callback', passport.authenticate('google', { failureRedirect: '/' }), (req, res) => { res.redirect('http://localhost:3000/dashboard'); } ); app.get('/api/current_user', (req, res) => { res.send(req.user); }); app.get('/auth/logout', (req, res) => { req.logout(() => { res.redirect('/'); }); }); app.listen(5000, () => console.log('Server running on http://localhost:5000'));

⚛️ Step 2: Set Up the Frontend (React)

1. Create your React app

cd .. npx create-react-app frontend cd frontend npm install axios

2. Create an AuthButton component

Create src/AuthButton.js:

import React, { useEffect, useState } from 'react';
import axios from 'axios'; const AuthButton = () => { const [user, setUser] = useState(null); useEffect(() => { axios.get('http://localhost:5000/api/current_user', { withCredentials: true }) .then(res => setUser(res.data)) .catch(() => setUser(null)); }, []); const login = () => { window.open('http://localhost:5000/auth/google', '_self'); }; const logout = () => { window.open('http://localhost:5000/auth/logout', '_self'); }; return ( <div> {user ? ( <> <h2>Welcome, {user.displayName}</h2> <button onClick={logout}>Logout</button> </> ) : ( <button onClick={login}>Login with Google</button> )} </div> ); }; export default AuthButton;

3. Use the AuthButton in App.js

import React from 'react'; import AuthButton from './AuthButton'; function App() { return ( <div className="App"> <h1>OAuth Demo</h1> <AuthButton /> </div> ); } export default App;

🚀 Running the App

  1. Start the backend:

cd backend node index.js
  1. Start the frontend:

cd ../frontend
npm start

Make sure your Google OAuth credentials allow http://localhost:5000/auth/google/callback as an authorized redirect URI.


âś… Conclusion

Now you've set up a simple OAuth authentication system using Node.js, Passport, and React. This setup can be extended to include user sessions, persistent storage, different OAuth providers, and much more.

Want to take it further? Try integrating:

  • JWT tokens instead of sessions

  • MongoDB to store users

  • GitHub or Facebook OAuth