Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

240
Views
How to use one function within multiple files in node.js

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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

express middleware

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!