iTranslated by AI
The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🚰
Resolving the "API resolved without sending a response" error in Next.js
In Next.js, the following error sometimes occurs:
API resolved without sending a response for /api/hello,
this may result in stalled requests.
This mainly happens when you forget res.end() or do not use res.json(), failing to properly handle the termination of the response.
export default async (req, res) => {
const { status } = await axios.get("https://example.com")
res.status(status)
// Should be res.status(status).end()
}
In the above case, not only is a warning issued, but you must also be careful as unnecessary charges may occur in environments like Cloud Run.
Cases occurring due to Middleware implementation
This can also happen depending on how middleware is written.
For example, it occurs when writing something like this:
const exampleMiddleware = (handler: NextApiHandler) => {
return (req, res) => {
console.log("this is example middleware!")
handler(req, res)
}
}
async function someHandler(req, res) {
const { status } = await axios.get("https://example.com")
res.status(status).end()
}
export default exampleMiddleware(someHandler)
At first glance, it seems that .end() is being called, but the problem lies within exampleMiddleware.
Solution
Return the handler using return.
const exampleMiddleware = (handler: NextApiHandler) => {
return (req, res) => {
console.log("this is example middleware!")
// handler(req, res) <- This causes a warning
return handler(req, res)
}
}
Or describe it in async/await format:
const exampleMiddleware = (handler: NextApiHandler) => {
return async (req, res) => {
console.log("this is example middleware!")
await handler(req, res)
}
}
References:
Discussion