Reputation: 68
So i have this one function which i am defining in my checkIfLogin.js
function authCheck (req, res, next) {
if (req.session.loggedin) {
next();
} else {
res.render('login.ejs')
}
}
I want to use this function for e.g. in my dashboard.js
, and clients.js
page as well. How can i export function from one page and use it in ALL pgaes in my app. I have a main index.js
file within my root dir that hosts all the imported files, but how can i import something like this to use the function within ALL files in my project?
Upvotes: 1
Views: 800
Reputation: 373
Use modules:
Export your function in checkIfLogin.js
:
exports.authCheck = function authCheck (req, res, next) {
if (req.session.loggedin) {
next();
} else {
res.render('login.ejs')
}
}
Import your function in otherFile.js
:
var authCheck = require('./checkIfLogin.js').authCheck;
The string in require
is your file path.
another approach
if you want to call this function before or after any api route you can use middleware
Upvotes: 1