0

I'm getting an error API resolved without sending a response for /api/getPuzzle?puzzleName=00-foo&lang=en, this may result in stalled requests. for an API handler in NextJS:

export default function handler(req: NextApiRequest, res: NextApiResponse) {
  let { puzzleName, lang } = req.query;
  const libraryDirectory = path.join(process.cwd(), 'library');
  try {
    fs.readFile(
      libraryDirectory + '/prompts/' + lang + '/' + puzzleName + '.' + lang,
      'utf-8',
      function (err, data) {
        if (err) {
          console.log('error in reading from library of prompts fs>>>', err);
          res.status(500).send({ success: false });
          return;
        }
        console.log(data);
        return res.status(200).send({ data });
      }
    );
  } catch (e) {
    console.error('error in fs>>', e);
  }
}

I'm not using getserversideprops or anything like that. Thank you.

reactor
  • 1,722
  • 1
  • 14
  • 34
  • Because you are sending the responses inside `readFile`'s callback. They should be sent at the top level of the `try/catch` block. – ivanatias Feb 08 '23 at 05:46
  • @ivanatias sorry, I don't understand why sending responses in a callback is an issue. can you provide a sample of working code? – reactor Feb 08 '23 at 05:58
  • You can check [this thread](https://stackoverflow.com/questions/72419522/whats-the-proper-way-for-returning-a-response-using-formidable-on-nextjs-api). Not exactly the same use case but the principle is the same. It's the `handler` that must send the responses. – ivanatias Feb 08 '23 at 06:24
  • @ivanatias thank you. I'll ask how this works since I feel like they're effectively identical. – reactor Feb 08 '23 at 07:20

0 Answers0