pixelcraft / backend /src /middleware /optionalAuth.js
monumkp89's picture
Deploy PixelCraft web app
b63786a verified
Raw History Blame Contribute Delete
429 Bytes
const jwt = require('jsonwebtoken');
const optionalAuth = (req, res, next) => {
const token = req.headers.authorization?.split(' ')[1];
if (!token) {
next();
return;
}
try {
const decoded = jwt.verify(token, process.env.JWT_SECRET);
req.userId = decoded.userId;
} catch (error) {
// Ignore invalid optional auth and continue as a public request.
}
next();
};
module.exports = optionalAuth;