How to use OAuth in Node.js

OAuth authentication enables secure third-party login integration in Node.js applications without handling user passwords directly. As the creator of CoreUI with extensive Node.js development experience since 2014, I’ve implemented OAuth flows in numerous enterprise applications for simplified user onboarding. The most reliable approach uses Passport.js with OAuth strategy packages to handle the complex authentication flow automatically. This method provides secure authentication while offering users familiar login options from popular platforms like Google, GitHub, or Facebook.

Implement OAuth authentication using Passport.js with Google OAuth strategy for secure social login.

const passport = require('passport')
const GoogleStrategy = require('passport-google-oauth20').Strategy

// Configure Google OAuth strategy
passport.use(new GoogleStrategy({
    clientID: process.env.GOOGLE_CLIENT_ID,
    clientSecret: process.env.GOOGLE_CLIENT_SECRET,
    callbackURL: '/auth/google/callback'
  },
  async (accessToken, refreshToken, profile, done) => {
    try {
      // Check if user exists
      let user = await User.findOne({ googleId: profile.id })

      if (user) {
        return done(null, user)
      } else {
        // Create new user
        user = new User({
          googleId: profile.id,
          name: profile.displayName,
          email: profile.emails[0].value,
          avatar: profile.photos[0].value
        })
        await user.save()
        return done(null, user)
      }
    } catch (error) {
      return done(error, null)
    }
  }
))

// OAuth routes
app.get('/auth/google',
  passport.authenticate('google', { scope: ['profile', 'email'] })
)

app.get('/auth/google/callback',
  passport.authenticate('google', { failureRedirect: '/login' }),
  (req, res) => {
    res.redirect('/dashboard')
  }
)

// Logout route
app.get('/logout', (req, res) => {
  req.logout()
  res.redirect('/')
})

This code configures Google OAuth authentication where users are redirected to Google for login, then returned to your application with authentication data. The strategy callback either finds an existing user or creates a new one based on the Google profile information. The OAuth flow handles all security aspects including token validation and user verification automatically.

Best Practice Note:

This is the OAuth implementation pattern we use in CoreUI dashboard applications for seamless social authentication. Always store OAuth tokens securely and implement proper error handling for failed authentication attempts to maintain security and user experience.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author

Subscribe to our newsletter
Get early information about new products, product updates and blog posts.
What Does javascript:void(0) Mean?
What Does javascript:void(0) Mean?

How to Remove Underline from Link in CSS
How to Remove Underline from Link in CSS

How to Use JavaScript setTimeout()
How to Use JavaScript setTimeout()

Mastering Inline Styles in React.js: Enhancing Your Components with Style
Mastering Inline Styles in React.js: Enhancing Your Components with Style

Answers by CoreUI Core Team