I am using the Express.Router class to create modular route handlers. When I go to define the route:
router.post('/dashboard/seo/update', checkAuth, dashboardController.updateSeo); I get an error: Route.post() requires a callback function but got a [object Object]
Upon Logging output it turns out that the checkAuth variable in the routes file is being set as an object and not a function. With my limited knowledge of JavaScript I am pretty sure that I am exporting checkAuth as a function using module.exports = checkAuth but I don't know why I am getting this error. For context this is my checkAuth function:
const admin = require('../Firebase/firebaseConfig');
// Middleware for checking if user is logged in
function checkAuth(req, res, next) {
let loggedIn = false;
// Check if the cookies exist and if the loggedIn cookie is set.
if (req.cookies && req.cookies.developerIn) {
// If it is, set loggedIn to true.
loggedIn = true;
// Verify the session cookie
admin.auth().verifySessionCookie(req.cookies.developerIn, true)
.then((decodedClaims) => {
// Add the user's UID to the request object
req.uid = decodedClaims.uid;
// Continue to the next middleware function
next();
})
.catch((error) => {
// If the session cookie is invalid, redirect to the login page
console.error('Failed to verify session cookie:', error);
res.status(401).redirect('/login');
});
} else {
// If the cookies don't exist or the loggedIn cookie isn't set, redirect to the login page
res.redirect('/login');
}
}
module.exports = checkAuth;
And my routes file where I am initializing the checkAuth object:
const router = express.Router();
const dashboardController = require('../controllers/dashboardController');
const checkAuth = require('../middleware/authmiddleware');
//Check if dashboardController.updateSeo is a function
console.log("Dashoard controller is a: ", typeof dashboardController.updateSeo);
console.log("Checkauth is a: ", typeof checkAuth); //Returns an object
router.post('/dashboard/seo/update', checkAuth, dashboardController.updateSeo);
module.exports = router;
I have tried to clear the required cache before importing the checkAuth function like this:
`delete require.cache[require.resolve('../middleware/authmiddleware')];
const checkAuth = require('../middleware/authmiddleware'); `
This does not solve the issue either. Any possible reasons that even with correct syntax, this error still persists? Am I missing something altogether?