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

115
Views
Node.js - Functions from another file as parameter in a route

I'm trying to make my program a bit more modular because it's quite a mess now. But for every attempt at refactoring my code I always get a bunch of errors and a program that doesn't work.

What I want to do is create multiple files that have their own workload and if I need something of it in another file, I can basically "borrow" that function.

Example from my existing code :

Index.js

//Routers 
const getPostsRouter = require('./routes/getPosts');
app.use('/getPosts', getPostsRouter);

///////////////////////////////////////////////////////////////////////////////////////////////

const authenticateToken = (req, res, next) => {
    const authHeader = req.headers['authorization'];
    const token = authHeader && authHeader.split(' ')[1]
    if (token == null) return res.sendStatus(401);

    jwt.verify(token, process.env.ACCESS_TOKEN_SECRET, (err, user) => {
        if (err) return res.sendStatus(403);
        req.user = user
        next()
    })
}

module.exports = authenticateToken;

Then in my getPosts.js file I want to be able to do something like

const express = require('express');
const router = express.Router();
const db = require('../databaseConnection');
const {authenticateToken} = require('../index')

router.get('/', authenticateToken, async (req, res) => {
        await db.query('SELECT * FROM posts', 
        (err, result) => {
            if (err) {
                res.send({errorMessage: err});
            }
            res.send(result);
        });
    }
}); 

module.exports = router;

But I always get this error when I try this : "Error: Route.get() requires a callback function but got a [object Undefined]" which points to the line "const getPostsRouter = require('./routes/getPosts');" in index.js

EDIT: The problem lied in circular dependencies! All I needed to do was erase one side of the dependency and now everything works as intended!

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

0

Remove the brackets, because you're always exporting authenticateToken by defualt...

const express = require('express');
const router = express.Router();
const db = require('../databaseConnection');
const authenticateToken = require('../index'); // <---- HERE

router.get('/', authenticateToken, async (req, res) => {
        await db.query('SELECT * FROM posts', 
        (err, result) => {
            if (err) {
                res.send({errorMessage: err});
            }
            res.send(result);
        });
    }
}); 

module.exports = router;
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!