Next.js Discord

Discord Forum

App Router Handler not returning Response inside then catch

Answered
devjiwonchoi posted this in #help-forum
Open in Discord
When using .then and .catch, it should return inside then if there is no error, but it seems like not returning the Response and giving error error TypeError: Cannot read properties of undefined (reading 'headers').
Why is it not returning?

Repro:

import { NextApiHandler } from 'next'
import { NextResponse } from 'next/server'
import axios from 'axios'

export const GET: NextApiHandler = () => {
  axios
    .get('https://jsonplaceholder.typicode.com/posts')
    .then((response) => {
      return NextResponse.json({ data: response.data[0] }, { status: 200 })
    })
    .catch((error) => {
      return NextResponse.json({ error: error.message }, { status: 500 })
    })
}


P.S. I know using NextApiHandler is weird but surprisingly it works.
Answered by aardani
axios is run syncrhonously so it just went straight pass through and since there isn't any NextResponse return in GET function, it will throw 500 Internal server error
View full answer

13 Replies

Yes, I know a right way to handle it, but faced someone's issue with this and was confused why its not returning.
Could you elaborate more on
the GET function ends right after invoking axios.get()
its basically because the axios.get function is not awaited. and API handler does not run indefinetly/it might be that its not persisted in the memory
axios is run syncrhonously so it just went straight pass through and since there isn't any NextResponse return in GET function, it will throw 500 Internal server error
Answer
Got it. Thank you!
Can I get your GitHub username? I'll credit for this reply
its in my profile
@joulev @aardani Hey, think we missed a big thing. We were not returning the axios 😂
 export const GET: NextApiHandler = () => 
  axios.get(//...
yeah that's the issue. i think the wrong type here played a role, the type is not NextApiHandler but (request: Request) => Promise<Response> | Response
so you might want to do export function GET(): Response instead
then ts will alert you that the type is wrong