JWT Malformed Error in Node.js/Express Application with Refresh Token Implementation

I’m encountering a JWT malformed error in my Node.js/Express application when trying to implement a refresh token mechanism. This error occurs every time I try to access a route that requires the JWT, including the /refresh-token route.

{
    "status": "error",
    "error": {
        "name": "JsonWebTokenError",
        "message": "jwt malformed",
        "statusCode": 500,
        "status": "error"
    },
    "message": "jwt malformed",
    "stack": "JsonWebTokenError: jwt malformedn    at module.exports (C:\path\to\node_modules\jsonwebtoken\verify.js:63:17)n    at ... (stack trace continues)"
}
JWT_SECRET=rainbow-six-siege-is-the-best-video-game-ever-made
JWT_EXPIRES_IN=3m
JWT_COOKIE_EXPIRES_IN=90

JWT_REFRESH=one-piece-is-best-anime-of-all-time-he-is-better-then-coding
JWT_REFRESH_EXPIRES=7d
JWT_REFRESH_COOKIE_EXPIRES_IN=10d
const jwt = require('jsonwebtoken');

const signToken = id => {
  return jwt.sign({ id }, process.env.JWT_SECRET, {
    expiresIn: process.env.JWT_EXPIRES_IN,
  });
};

const signRefreshToken = id => {
  return jwt.sign({ id }, process.env.JWT_REFRESH, {
    expiresIn: process.env.JWT_REFRESH_EXPIRES,
  });
};
const createSendToken = (user, statusCode, res) => {
  const token = signToken(user._id);
  const cookieOptions = {
    expires: new Date(Date.now() + parseInt(process.env.JWT_COOKIE_EXPIRES_IN, 10) * 24 * 60 * 60 * 1000),
    httpOnly: true,
  };

  if (process.env.NODE_ENV === 'production') cookieOptions.secure = true;
  res.cookie('jwt', token, cookieOptions);

  user.password = undefined;

  res.status(statusCode).json({
    status: 'success',
    token,
    data: { user },
  });
};

const createSendRefreshToken = (user, statusCode, res) => {
  const token = signRefreshToken(user._id);
  const cookieOptions = {
    expires: new Date(Date.now() + parseInt(process.env.JWT_REFRESH_COOKIE_EXPIRES_IN, 10) * 24 * 60 * 60 * 1000),
    httpOnly: true,
  };

  if (process.env.NODE_ENV === 'production') cookieOptions.secure = true;
  res.cookie('jwt', token, cookieOptions);

  user.password = undefined;

  res.status(statusCode).json({
    status: 'success',
    token,
    data: { user },
  });
};
exports.refreshToken = catchAsync(async (req, res, next) => {
  const token = req.cookies.jwt;

  if (!token) {
    return next(new AppError('You need to log in!', 401));
  }

  try {
    const decoded = await promisify(jwt.verify)(token, process.env.JWT_REFRESH);
    const user = await User.findById(decoded.id);

    if (!user) {
      return next(new AppError('The user belonging to this token no longer exists.', 401));
    }

    createSendToken(user, 200, res);
    createSendRefreshToken(user, 200, res);

  } catch (err) {
    return next(new AppError('Token is invalid or has expired', 401));
  }
});

Certainly! Below is a well-structured question you can post on Stack Overflow regarding your "jwt malformed" issue, along with the relevant code and details.


Title:

JWT Malformed Error in Node.js/Express Application with Refresh Token Implementation

Body:

I’m encountering a JWT malformed error in my Node.js/Express application when trying to implement a refresh token mechanism. This error occurs every time I try to access a route that requires the JWT, including the /refresh-token route.

Error Message:

json

Copier le code

{ “status”: “error”, “error”: { “name”: “JsonWebTokenError”, “message”: “jwt malformed”, “statusCode”: 500, “status”: “error” }, “message”: “jwt malformed”, “stack”: “JsonWebTokenError: jwt malformedn at module.exports (C:\path\to\node_modules\jsonwebtoken\verify.js:63:17)n at … (stack trace continues)” }

.env File:

plaintext

Copier le code

JWT_SECRET=rainbow-six-siege-is-the-best-video-game-ever-made JWT_EXPIRES_IN=3m JWT_COOKIE_EXPIRES_IN=90 JWT_REFRESH=one-piece-is-best-anime-of-all-time-he-is-better-then-coding JWT_REFRESH_EXPIRES=7d JWT_REFRESH_COOKIE_EXPIRES_IN=10d

Relevant Code:

  1. JWT Token Signing Functions:
javascript

Copier le code

const jwt = require(‘jsonwebtoken’); const signToken = id => { return jwt.sign({ id }, process.env.JWT_SECRET, { expiresIn: process.env.JWT_EXPIRES_IN, }); }; const signRefreshToken = id => { return jwt.sign({ id }, process.env.JWT_REFRESH, { expiresIn: process.env.JWT_REFRESH_EXPIRES, }); };

  1. Create and Send Tokens:
javascript

Copier le code

const createSendToken = (user, statusCode, res) => { const token = signToken(user._id); const cookieOptions = { expires: new Date(Date.now() + parseInt(process.env.JWT_COOKIE_EXPIRES_IN, 10) * 24 * 60 * 60 * 1000), httpOnly: true, }; if (process.env.NODE_ENV === ‘production’) cookieOptions.secure = true; res.cookie(‘jwt’, token, cookieOptions); user.password = undefined; res.status(statusCode).json({ status: ‘success’, token, data: { user }, }); }; const createSendRefreshToken = (user, statusCode, res) => { const token = signRefreshToken(user._id); const cookieOptions = { expires: new Date(Date.now() + parseInt(process.env.JWT_REFRESH_COOKIE_EXPIRES_IN, 10) * 24 * 60 * 60 * 1000), httpOnly: true, }; if (process.env.NODE_ENV === ‘production’) cookieOptions.secure = true; res.cookie(‘jwt’, token, cookieOptions); user.password = undefined; res.status(statusCode).json({ status: ‘success’, token, data: { user }, }); };

  1. Refresh Token Route:
javascript

Copier le code

exports.refreshToken = catchAsync(async (req, res, next) => { const token = req.cookies.jwt; if (!token) { return next(new AppError(‘You need to log in!’, 401)); } try { const decoded = await promisify(jwt.verify)(token, process.env.JWT_REFRESH); const user = await User.findById(decoded.id); if (!user) { return next(new AppError(‘The user belonging to this token no longer exists.’, 401)); } createSendToken(user, 200, res); createSendRefreshToken(user, 200, res); } catch (err) { return next(new AppError(‘Token is invalid or has expired’, 401)); } });

Steps Taken:

  • Verified the .env file for any incorrect configuration. Originally, there was an extra space before the JWT_REFRESH value, which I have since removed.

  • Added logs to track the token generation and retrieval, but still no logs appear before the error.

  • Restarted the server multiple times after any changes.

My Assumptions:

  • The error might be related to the token generation or how it’s stored/retrieved from cookies.

  • There could still be a misconfiguration in environment variables, even though they now appear correct.

Question:

What could be causing the "jwt malformed" error in this context? Are there common pitfalls or things I might be overlooking when implementing JWTs, especially with refresh tokens?

Any help or insights would be greatly appreciated!

New contributor

Hamza Bounibane is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật