Topic 017: Custom middleware in MERN
source :
https://github.com/faizmhd/passport-app https://github.com/Samuel-Hall/Passport-JWT-MERN https://github.com/kalyansaxena/mern-authentication-jwt https://github.com/bradtraversy/mern-auth
authMiddleware.js
import jwt from "jsonwebtoken";
import asyncHandler from "express-async-handler";
import User from "../models/userModel.js";
const protect = asyncHandler(async (req, res, next) => {
let token;
token = req.cookies.jwt;
if (token) {
try {
const decoded = jwt.verify(token, process.env.JWT_SECRET);
req.user = await User.findById(decoded.userId).select("-password");
next();
} catch (error) {
console.error(error);
res.status(401);
throw new Error("Not authorized, token failed");
}
} else {
res.status(401);
throw new Error("Not authorized, no token");
}
});
export { protect };
errorMiddleware.js
const notFound = (req, res, next) => {
const error = new Error(`Not Found - ${req.originalUrl}`);
res.status(404);
next(error);
};
const errorHandler = (err, req, res, next) => {
let statusCode = res.statusCode === 200 ? 500 : res.statusCode;
let message = err.message;
// If Mongoose not found error, set to 404 and change message
if (err.name === "CastError" && err.kind === "ObjectId") {
statusCode = 404;
message = "Resource not found";
}
res.status(statusCode).json({
message: message,
stack: process.env.NODE_ENV === "production" ? null : err.stack,
});
};
export { notFound, errorHandler };