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

195
Views
Cannot set headers after they are sent to the client - Express JS

I am pretty much new to node / express and following a youtube tutorial to build a MERN Stack app. But my node server is giving this error

error

I tried restarting server many times it happening again and again. I got the idea it happens when we send two responses for one request but I don't think its the case here.

Btw here is the route it is pointing to in the error (in the try catch error response line)

// GET RANDOM
router.get("/random", verify, async (req, res) => {
    const type = req.query.type;
    let movie;
    try {
      if (type === "series") {
        movie = await Movie.aggregate([
          { $match: { isSeries: true } },
          { $sample: { size: 1 } },
        ]);
      } else {
        movie = await Movie.aggregate([
          { $match: { isSeries: false } },
          { $sample: { size: 1 } },
        ]);
      }
      res.status(200).json(movie); //checked here by console logging it comes here only once
    } catch (err) {
      res.status(500).json(err); //the error pointing to this line
    }
});

Just in case, here is the verify function code:

function verify(req,res,next) {
    const authHeader = req.headers.token;
    if(authHeader){
        const token = authHeader.split(' ')[1];

        jwt.verify(token,process.env.SECRET_KEY,(err,user) => {
            if(err) res.status(403).json("Token is not valid");
            req.user = user;
            next();
        })
    } else{
        return res.status(401).json("Unauthorized");
    }
}
about 4 years ago · Juan Pablo Isaza
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!