Tech TutorBangla Web Documentation
Portfolio
HomeHTMLCSSTailwind CSSJavaScriptTypeScriptReactNext.jsNode.jsExpressSocket.IOExpoWordPressPostgreSQLPrismaPostgresNestJSMongoDBDockerTanStackTanStack TableRTK QueryGitGitHub
  • Express Documentation22টি অধ্যায়
প্রযুক্তি নির্বাচন
HomeHTMLCSSTailwind CSSJavaScriptTypeScriptReactNext.jsNode.jsExpressSocket.IOExpoWordPressPostgreSQLPrismaPostgresNestJSMongoDBDockerTanStackTanStack TableRTK QueryGitGitHub
  • Introduction
  • Installation
  • Routing
  • Middleware
  • Request & Response
  • Static Files
  • Router
  • Error Handling
  • Template Engines
  • Body Parsing
  • File Upload
  • CORS
  • Database
  • Validation
  • Authentication
  • Security
  • REST API
  • Performance
  • Testing
  • Best Practices
  • Project
  • Interview
  1. Docs
  2. Express
  3. Express Authentication (JWT)
ExpressAdvanced

Express Authentication (JWT)

bcrypt, JWT, login/register, protected routes, middleware — Express auth বাংলায়।

13টি অংশবাংলা ভাষায়

Authentication login-এর মাধ্যমে user verify করা। সবচেয়ে জনপ্রিয় পদ্ধতি JWT (JSON Web Token) + bcrypt (password hash)।

অপরিহার্য Packages

npm install bcryptjs jsonwebtoken
.envenv
env
JWT_SECRET=your_super_secret_key
JWT_EXPIRES=1d

Register Route

controllers/authController.jsjavascript
javascript
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");
const User = require("../models/User");

// Register
const register = async (req, res, next) => {
  const { name, email, password } = req.body;

  try {
    const existing = await User.findOne({ email });
    if (existing) {
      return res.status(409).json({ error: "এই email ইতিমধ্যে আছে" });
    }

    const hashed = await bcrypt.hash(password, 10);

    const user = await User.create({
      name,
      email,
      password: hashed,
    });

    res.status(201).json({
      message: "Registration সফল",
      user: { id: user._id, name: user.name, email: user.email },
    });
  } catch (err) { next(err); }
};

// Login
const login = async (req, res, next) => {
  const { email, password } = req.body;

  try {
    const user = await User.findOne({ email });
    if (!user) {
      return res.status(401).json({ error: "Email বা password ভুল" });
    }

    const isMatch = await bcrypt.compare(password, user.password);
    if (!isMatch) {
      return res.status(401).json({ error: "Email বা password ভুল" });
    }

    const token = jwt.sign(
      { id: user._id, email: user.email },
      process.env.JWT_SECRET,
      { expiresIn: process.env.JWT_EXPIRES }
    );

    res.json({
      token,
      user: { id: user._id, name: user.name, email: user.email },
    });
  } catch (err) { next(err); }
};

module.exports = { register, login };

Auth Middleware

middleware/auth.jsjavascript
javascript
const jwt = require("jsonwebtoken");
const User = require("../models/User");

const protect = async (req, res, next) => {
  let token;

  // Authorization: Bearer <token>
  if (req.headers.authorization?.startsWith("Bearer")) {
    token = req.headers.authorization.split(" ")[1];
  }

  if (!token) {
    return res.status(401).json({ error: "Login প্রয়োজন" });
  }

  try {
    const decoded = jwt.verify(token, process.env.JWT_SECRET);
    const user = await User.findById(decoded.id).select("-password");

    if (!user) {
      return res.status(401).json({ error: "User পাওয়া যায়নি" });
    }

    req.user = user;
    next();
  } catch (err) {
    return res.status(401).json({ error: "Token invalid/expired" });
  }
};

// Role-based authorization
const authorize = (...roles) => (req, res, next) => {
  if (!roles.includes(req.user.role)) {
    return res.status(403).json({ error: "অনুমতি নেই" });
  }
  next();
};

module.exports = { protect, authorize };

Protected Route

const { protect } = require("../middleware/auth");

// protected
app.get("/api/profile", protect, (req, res) => {
  res.json({ user: req.user });
});

// only student
app.post("/api/assignment", protect, authorize("student"), (req, res) => {
  res.json({ message: "Assignment submitted" });
});

Client ব্যবহার

Fetch example (client side)javascript
javascript
// login → token
const loginRes = await fetch("/api/auth/login", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ email, password }),
});
const { token } = await loginRes.json();

// protected API call
const data = await fetch("/api/profile", {
  headers: {
    Authorization: "Bearer " + token,
  },
}).then((r) => r.json());
গুরুত্বপূর্ণ

password কখনো plain-এ store করবেন না — সবসময় bcrypt hash। JWT secret strong রাখুন (.env) এবং expiry দিন।

শেষ প্যারায় নিজে practice করুন — কোড কপি করে নিজের এডিটরে চালিয়ে দেখুন।
আগেরExpress Input Validation (Zod)পরেরExpress Security Best Practices
এই পেজে
Tech Tutor

বাংলায় ওয়েব ডেভেলপমেন্ট ডকুমেন্টেশন শিখুন — ধাপে ধাপে।

Homeসব ডকুমেন্টেশনQuick Startআমার নোটস

© 2026 Tech Tutor. বাংলায় শিখুন, বাংলায় গড়ুন।

mdanamolhasan1998@gmail.com