next.js: False positive report of "API resolved without sending a response"

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

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Reactions: 12
  • Comments: 28 (10 by maintainers)

Commits related to this issue

Most upvoted comments

@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()
  })
}
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,
  },
}

I see the same warning with apollo-server-express.

@iddify please provide code instead of saying “same issue”, it’s unlikely that you’re doing 100% exactly the same as the person that posts an issue.

Looks like you’re not finishing the request when a body is not set:

  if (!req.body) {
    return res.status(400);
  }

Should be:

  if (!req.body) {
    return res.status(400).send({});
  }

I had the same issue with the following code:

export default async (req: NextApiRequest, res: NextApiResponse) => {
	if (req.method === 'POST') {
		handlePost(req, res)
		return
	}

	if (req.method === 'GET') {
	       handleGet(req, res)
	       return
	}

	res.status(405).send('Method not allowed')
}

What solved it for me was awaiting both handlers, like so: await handlePost(req, res).

I’m having the same problem. Why is this issue closed? Is this a problem from Next server or am I doing something wrong?

I havent been able to figure it out yet. Im considering to switch to express server to handle all requests. (Instead of just api)

@timneutkens Thank you for the quick reply. Unfortunately 9.2.2-canary.12 doesn’t solve the issue 😞

I don’t know exactly how Next analyzes whether or not a route actually returns something, but it could be because of the callback in http.request or the try/catch ?

I also wonder if this couldn’t be because of the http.request function that could “silently” fail and just not do anything 🤔

I will investigate a bit more 👍