OAuth client for JavaScript (Node.js): complete guide
OAuth (Open Authorization) is an open protocol that allows a third-party application to be granted limited access to a user's resources without transmitting their login and password. In the Node.js world, implementing an OAuth client is one of the most common tasks when building modern web applications. In this article, we will thoroughly examine how to write your own OAuth client for authorization via Google and GitHub, using the popular library Passport.js.
What is OAuth 2.0 and why is it needed?
OAuth 2.0 is a standard used for delegating access. Instead of storing user passwords on your server, you redirect them to the provider's page (Google, GitHub, Facebook), where they give their consent. After that, your application receives an access token, with which it can access the provider's API on behalf of the user.
Main advantages:
- Security — passwords are not stored on your server.
- Convenience for the user — no need to register again.
- Flexibility — you can request only the data that is actually needed (scope).
Installing required packages
To work with OAuth in Node.js, we will use the following libraries:
express— web frameworkpassport— authentication middlewarepassport-google-oauth20— strategy for Googlepassport-github2— strategy for GitHubexpress-session— for storing sessions
Install them with one command:
npm install express passport passport-google-oauth20 passport-github2 express-sessionBasic server setup
Let's create a file app.js and include all the necessary modules:
const express = require('express');const passport = require('passport');const session = require('express-session');const app = express();
// Session setupapp.use(session({ secret: 'your-secret-key', resave: false, saveUninitialized: true}));
app.use(passport.initialize());app.use(passport.session());
// Placeholder for user serializationpassport.serializeUser((user, done) => done(null, user));passport.deserializeUser((obj, done) => done(null, obj));
app.listen(3000, () => console.log('Server running on port 3000'));Setting up the OAuth strategy for Google
Before starting, you need to register your application in the Google Cloud Console and obtain a Client ID and Client Secret. Specify the redirect URI in the settings: http://localhost:3000/auth/google/callback.
const GoogleStrategy = require('passport-google-oauth20').Strategy;
passport.use(new GoogleStrategy({ clientID: 'YOUR_GOOGLE_CLIENT_ID', clientSecret: 'YOUR_GOOGLE_CLIENT_SECRET', callbackURL: 'http://localhost:3000/auth/google/callback'}, (accessToken, refreshToken, profile, done) => { // Here you can save the profile to the database return done(null, profile);}));
// Routes for Google OAuthapp.get('/auth/google', passport.authenticate('google', { scope: ['profile', 'email'] }));
app.get('/auth/google/callback', passport.authenticate('google', { failureRedirect: '/' }), (req, res) => res.redirect('/profile'));Setting up the OAuth strategy for GitHub
For GitHub, register an OAuth App in the GitHub Developer Settings. Homepage URL: http://localhost:3000, Authorization callback UR
Also in library
HTTP Client for Swift (iOS/macOS): Top Libraries for Networking
Caching in Kotlin: Redis, Caffeine and Ehcache — A Complete Guide
Logging in Go: Overview of the Standard log Library and Alternatives
WebSocket Libraries TypeScript: ws, Socket.IO, uWebSockets.js