Header sent error express.js with cookie-parser

I am build backend server. I use express.js, jsonwebtoken and cookie-parser for user authentication. I define middleware functions:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>const protect = catchAsync(async (req, res, next) => {
// 1) Getting token and check of it's there
let token;
if (req.cookies.jwt) {
token = req.cookies.jwt;
}
if (!token) {
return next(
new AppError('You are not logged in! Please log in to get access.', 401)
);
}
const decoded = await promisify(jwt.verify)(token, process.env.JWT_SECRET);
const currentUser = await Users.findByPk(decoded.id);
if (!currentUser) {
return next(
new AppError(
'The user belonging to this token does no longer exist.',
401
)
);
}
req.user = currentUser.toJSON();
return next();
});
</code>
<code>const protect = catchAsync(async (req, res, next) => { // 1) Getting token and check of it's there let token; if (req.cookies.jwt) { token = req.cookies.jwt; } if (!token) { return next( new AppError('You are not logged in! Please log in to get access.', 401) ); } const decoded = await promisify(jwt.verify)(token, process.env.JWT_SECRET); const currentUser = await Users.findByPk(decoded.id); if (!currentUser) { return next( new AppError( 'The user belonging to this token does no longer exist.', 401 ) ); } req.user = currentUser.toJSON(); return next(); }); </code>
const protect = catchAsync(async (req, res, next) => {
  // 1) Getting token and check of it's there
  let token;
  if (req.cookies.jwt) {
    token = req.cookies.jwt;
  }
if (!token) {
    return next(
      new AppError('You are not logged in! Please log in to get access.', 401)
    );
  }
  const decoded = await promisify(jwt.verify)(token, process.env.JWT_SECRET);
  const currentUser = await Users.findByPk(decoded.id);
  if (!currentUser) {
    return next(
      new AppError(
        'The user belonging to this token does no longer exist.',
        401
      )
    );
  }

  req.user = currentUser.toJSON();

  return next();
});

After I do restrictTo :

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>const restrictTo = async (req, res, next) => {
const { permissions } = req.user.role;
permissions.forEach((element) => {
const { method, path, name } = element;
if (req.method.toLowerCase() === method.toLowerCase()) {
const ok = checkUrl(req.originalUrl, path);
if (ok) {
console.log('gedo');
return next();
}
}
});
return next(new AppError('you dont have permission', 403));
};
</code>
<code>const restrictTo = async (req, res, next) => { const { permissions } = req.user.role; permissions.forEach((element) => { const { method, path, name } = element; if (req.method.toLowerCase() === method.toLowerCase()) { const ok = checkUrl(req.originalUrl, path); if (ok) { console.log('gedo'); return next(); } } }); return next(new AppError('you dont have permission', 403)); }; </code>
const restrictTo = async (req, res, next) => {
  const { permissions } = req.user.role;
  permissions.forEach((element) => {
    const { method, path, name } = element;
    if (req.method.toLowerCase() === method.toLowerCase()) {
      const ok = checkUrl(req.originalUrl, path);
      if (ok) {
        console.log('gedo');
        return next();
      }
    }
  });
  return next(new AppError('you dont have permission', 403));
};

Here I simple define route:
router.route('/').get(protect, restrictTo, getAllCountry);
I get response successfully. But when see console.log I see this error:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at new NodeError (node:internal/errors:405:5)
</code>
<code>Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client at new NodeError (node:internal/errors:405:5) </code>
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at new NodeError (node:internal/errors:405:5)

How can I fix this?

I just looked your code and it seems like you made a small mistake in your restrictTo function. You used a forEach loop and return next(); is executed again after the response has already been sent. To fix this, you can use a flag variable and if the flag has correct value, return next(); is executed.

I provide updated code:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>const restrictTo = (req, res, next) => {
const { permissions } = req.user.role;
let isRightPermission = false;
permissions.forEach((element) => {
const { method, path, name } = element;
if (req.method.toLowerCase() === method.toLowerCase()) {
const ok = checkUrl(req.originalUrl, path);
if (ok) {
isRightPermission = true;
}
}
});
if (isRightPermission) {
return next();
}
return next(new AppError('You don’t have permission', 403));
};
</code>
<code>const restrictTo = (req, res, next) => { const { permissions } = req.user.role; let isRightPermission = false; permissions.forEach((element) => { const { method, path, name } = element; if (req.method.toLowerCase() === method.toLowerCase()) { const ok = checkUrl(req.originalUrl, path); if (ok) { isRightPermission = true; } } }); if (isRightPermission) { return next(); } return next(new AppError('You don’t have permission', 403)); }; </code>
const restrictTo = (req, res, next) => {
  const { permissions } = req.user.role;
  
  let isRightPermission = false;

  permissions.forEach((element) => {
    const { method, path, name } = element;
    if (req.method.toLowerCase() === method.toLowerCase()) {
      const ok = checkUrl(req.originalUrl, path);
      if (ok) {
        isRightPermission = true;
      }
    }
  });

  if (isRightPermission) {
    return next();
  }

  return next(new AppError('You don’t have permission', 403));
};

0

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