Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

next.js Api route give me warning like / API resolved without sending a response for /api/*** this may result in stalled requests

Tags:

axios

next.js

I'm using next.js API Route with axios and my api gives me warning below

API resolved without sending a response for /api/authentication/login, this may result in stalled requests.

I can't find what I'm doing wrong

import axios from 'axios'
import type { NextApiRequest, NextApiResponse } from 'next'

const handler = (req: NextApiRequest, res: NextApiResponse): void => {
  axios({
    method: 'post',
    headers : { 'Content-type': 'application/json' },
    url: `${process.env.WEB_API_URL}/authentication/login`,
    data: req.body,
  })
    .then((results) => {
      res.status(results.status).json(results.data)
    })
    .catch((error) => {
      res.status(error.status).json(error.response.data)
    })
}

export default handler
like image 450
yoru kim Avatar asked Oct 28 '25 14:10

yoru kim


1 Answers

You have a promise there (your axios request) and you should return that. What's happening is that your api function is being called, a promise is kicked off, but the processing for your api call continues to the end (without waiting for the promise to resolve), and the api call ends with no response. You can solve this one of two ways - return the promise, or await the results of the axios call:

// Option 1 - return the promise
import axios from 'axios'
import type { NextApiRequest, NextApiResponse } from 'next'

const handler = (req: NextApiRequest, res: NextApiResponse): Promise<void> => {
  return axios({
    method: 'post',
    headers : { 'Content-type': 'application/json' },
    url: `${process.env.WEB_API_URL}/authentication/login`,
    data: req.body,
  })
    .then((results) => {
      res.status(results.status).json(results.data)
    })
    .catch((error) => {
      res.status(error.status).json(error.response.data)
    })
}

export default handler
// Option 2 - wait for the promise to resolve
import axios from 'axios'
import type { NextApiRequest, NextApiResponse } from 'next'

const handler = async (req: NextApiRequest, res: NextApiResponse): Promise<void> => {
  try {
    const results = await axios({
      method: 'post',
      headers : { 'Content-type': 'application/json' },
      url: `${process.env.WEB_API_URL}/authentication/login`,
      data: req.body,
    })
    res.status(results.status).json(results.data)
  } catch (error) {
    res.status(error.status).json(error.response.data)
  }
}

export default handler

Note that I added Promise to your function return signature, but Promise<void> is not right. I don't know anything about your data structure, so you'd want to change void to whatever that actually looks like.

like image 119
I'm Joe Too Avatar answered Oct 31 '25 11:10

I'm Joe Too



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!