Reputation: 980
in my middleware
folder, I have a file called auth.js
.
In this file, I have this function:
function authCheck () {
if (req.session.loggedin) {
return;
} else {
req.session.destory();
res.redirect('/login')
}
}
I need to export it, and then use it in my other files, so then I would need to import it inside of my root directory app.js
file, and my routes
folder, those js
files there.
I basically want to do this:
app.get('/index', authCheck, (req, res) => {
.....
}
how do I do this?
Upvotes: 1
Views: 2961
Reputation: 10490
You use app.use
assuming you're using expressjs and use next()
to continue the execution
auth.js
function authCheck (req, res, next) {
if (req.session.loggedin) {
next();
} else {
req.session.destory();
res.redirect('/login')
}
}
module.exports = { authCheck }
app.js
const {authCheck} = require('./auth.js');
app.use(authCheck)
app.get('/index', (req, res) => {
.....
}
Upvotes: 2
Reputation: 23622
You can create a middleware like auth.js file in it and add auth code in it like below:
module.exports = {
authCheck: (req, res, next) => {
}
}
And import that file in your route folder and use it like below:
const auth = require('../middlewares/auth')
router.post("/", auth.authCheck, (req, res, next) => {
});
Upvotes: 0
Reputation: 2059
Node modules is what you're looking for.
Here's an example from the nodejs documentation.
Export a function from addTwo.mjs
// addTwo.mjs
function addTwo(num) {
return num + 2;
}
export { addTwo };
Import and use the exported function in app.mjs
// app.mjs
import { addTwo } from './addTwo.mjs';
// Prints: 6
console.log(addTwo(4));
Note that the file extension.mjs
is used to specify that you're using es6 modules.
Read more here.
https://nodejs.org/api/esm.html#esm_introduction
Upvotes: 1