question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

False positive report of "API resolved without sending a response"

See original GitHub issue

Bug report

Describe the bug

Api endpoint

Next will log the “API resolved without sending a response” warning even though the API endpoint always send a response back.

To Reproduce

Here the code that triggers the warning:

export default async function(req: NextApiRequest, res: NextApiResponse) {
  switch (req.method) {
    case "POST":
    case "OPTION": {
      try {
        const request = http.request( // Node core http module
          url,
          {
            headers: await makeHeaders(req, res),
            method: req.method,
          },
          response => {
            response.pipe(res);
          },
        );

        request.write(JSON.stringify(req.body));

        return request.end();
      } catch (error) {
        Log.error(error); // Can be a simple console.error too
      }

      return res.status(500).end();
    }
  }

  return res.status(405).end();
}

It seems that this endpoint will always send a response back.

Expected behavior

No warning

System information

  • OS: MacOS
  • Version of Next.js: 9.2.1

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Reactions:12
  • Comments:28 (9 by maintainers)

github_iconTop GitHub Comments

55reactions
ijjkcommented, Feb 7, 2020

@gaku-sei it is most likely caused by the callback as we can’t detect you are still doing work in the API unless you return a promise and wait to resolve it until after the callback is fired e.g.

export default async function(req: NextApiRequest, res: NextApiResponse) {
  return new Promise(resolve => {
    switch (req.method) {
      case "POST":
      case "OPTION": {
        try {
          const request = http.request( // Node core http module
            url,
            {
              headers: await makeHeaders(req, res),
              method: req.method,
            },
            response => {
              response.pipe(res);
              resolve()
            },
          );

          request.write(JSON.stringify(req.body));
          request.end();
        } catch (error) {
          Log.error(error); // Can be a simple console.error too
          res.status(500).end();
          return resolve()
        }
      }
    }
    res.status(405).end();
    return resolve()
  })
}
37reactions
timneutkenscommented, May 23, 2020
export default async function token(req, res) {
  try {
    const { user } = await auth0.getSession(req);

    if(!user) {
      throw new Error('No User');
    }

    const result = await fetch(`https://${process.env.domain}/oauth/token`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        grant_type: 'client_credentials',
        client_id: process.env.authClientID,
        client_secret: process.env.authClientSecret,
        audience: `https://${process.env.domain}/api/v2/`,
      }),
    })
    const { access_token, scope, expires_in, token_type } = await result.json()


    return { access_token, scope, expires_in, token_type }
  } catch (error) {
    console.error(error)
    return res.status(error.status || 500).end(error.message)
  }
}

This should solve your case, but you can now disable the warning also: https://nextjs.org/docs/api-routes/api-middlewares

// export this from the api route
export const config = {
  api: {
    externalResolver: true,
  },
}
Read more comments on GitHub >

github_iconTop Results From Across the Web

API resolved without sending a response in Nextjs
1: I have and alert message that says: API resolved without sending a response for /api/data, this may result in stalled requests. 2:...
Read more >
API resolved without sending a response for...this may result ...
I have successfully implemented an API that inserts values into my MySQL database. However, when I test my API, I get the following:...
Read more >
Api Resolved Without Sending A Response For /Api/Auth ...
Bug report. Describe the bug. Api endpoint. Next will log the API resolved without sending a response warning even though the API endpoint...
Read more >
Response Status and Error Codes - Infobip
Browse through the list of status and error codes that you might encounter to find out more about their meaning and how to...
Read more >
SafetyNet Attestation API - Android Developers
If the device is tampered—that is, if basicIntegrity is set to false in the response—the verdict might not contain data about the calling...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found