Back to Tutorials
Node.js
45 min read
Sahasransu Satpathy
4/5/2026

User Authentication (JWT & OAuth) in Node.js

Implement secure user authentication using JWT and OAuth in Node.js applications

Introduction

Authentication is a crucial part of web applications. In this tutorial, you'll learn JWT (JSON Web Tokens) and OAuth 2.0 implementation in Node.js to securely authenticate users.


Step 1: Project Setup

Initialize a new Node.js project and install dependencies:

mkdir node-auth
cd node-auth
npm init -y
npm install express mongoose bcryptjs jsonwebtoken passport passport-google-oauth20 dotenv

Create a start script in package.json:

"scripts": {
  "start": "nodemon index.js"
}

Step 2: User Model with Mongoose

Create a User schema:

const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');

const userSchema = new mongoose.Schema({
  username: { type: String, required: true },
  email: { type: String, required: true, unique: true },
  password: { type: String, required: true },
  googleId: String
});

// Hash password before saving
userSchema.pre('save', async function(next) {
  if(!this.isModified('password')) return next();
  this.password = await bcrypt.hash(this.password, 12);
  next();
});

const User = mongoose.model('User', userSchema);
module.exports = User;

Step 3: JWT Authentication

Register Route

const jwt = require('jsonwebtoken');
app.post('/register', async (req, res) => {
  const { username, email, password } = req.body;
  const user = new User({ username, email, password });
  await user.save();
  const token = jwt.sign({ id: user._id }, process.env.JWT_SECRET, { expiresIn: '1d' });
  res.json({ token, user });
});

Login Route

app.post('/login', async (req, res) => {
  const { email, password } = req.body;
  const user = await User.findOne({ email });
  if(!user) return res.status(404).json({ message: 'User not found' });

  const isMatch = await bcrypt.compare(password, user.password);
  if(!isMatch) return res.status(400).json({ message: 'Invalid credentials' });

  const token = jwt.sign({ id: user._id }, process.env.JWT_SECRET, { expiresIn: '1d' });
  res.json({ token, user });
});

Protect Routes Middleware

const authMiddleware = (req, res, next) => {
  const token = req.header('Authorization')?.replace('Bearer ', '');
  if(!token) return res.status(401).json({ message: 'No token provided' });

  try {
    const decoded = jwt.verify(token, process.env.JWT_SECRET);
    req.userId = decoded.id;
    next();
  } catch(err) {
    res.status(401).json({ message: 'Invalid token' });
  }
};

Step 4: OAuth 2.0 with Google

Passport Setup

const passport = require('passport');
const GoogleStrategy = require('passport-google-oauth20').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) => {
  let user = await User.findOne({ googleId: profile.id });
  if(!user) {
    user = await User.create({
      googleId: profile.id,
      username: profile.displayName,
      email: profile.emails[0].value
    });
  }
  done(null, user);
}));

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');
  });

Step 5: Testing

  • Test JWT authentication with Postman.
  • Try logging in via Google OAuth and verify user creation.

Step 6: Next Steps

  • Implement refresh tokens.
  • Add role-based access control.
  • Integrate frontend login forms with JWT or OAuth flows.

Conclusion

You now have a secure Node.js authentication system using JWT and OAuth, ready for full-stack applications.


SEO Suggestions:

  • Main keywords: Node.js authentication, JWT tutorial, OAuth Node.js, secure login Node.js, user authentication guide
  • Meta description: Learn to implement user authentication in Node.js using JWT and OAuth 2.0. Step-by-step guide with examples and best practices.
  • Catchy title suggestions: "User Authentication in Node.js – JWT & OAuth Guide 2026", "Secure Node.js Apps with JWT and OAuth"

Previous Tutorial

Browse All Tutorials