Next.js Discord

Discord Forum

TypeError: Response body object should not be disturbed or locked

Answered
Keyhole wasp posted this in #help-forum
Open in Discord
Avatar
Keyhole waspOP
I am getting this error with this api route code.
import { analyzeTrackSegment } from '@/lib/bedrock'
import { NextRequest } from 'next/server'

interface ResponseBody {
  images: string[]
  startIndex: number
  endIndex: number
  scale: number
}

export async function POST(request: NextRequest): Promise<Response> {
  const { images, startIndex, endIndex, scale }: ResponseBody = await request.json()
  const imagesData: { contentType: string; imageData: string }[] = []

  for (const image of images) {
    const contentType = image.split(';')[0].split(':')[1]
    const imageData = image.replace(/^data:image\/(jpeg|png);base64,/, '')
    imagesData.push({ contentType, imageData })
  }

  const result = await analyzeTrackSegment({ startIndex, endIndex, imagesData, scale })
  if (result) return new Response(JSON.stringify(result), { status: 200 })
  else return new Response('Failed to analyze track segment', { status: 500 })
}

I've seen other people have this error with DELETE but im using POST so not sure why its happening.

It also only happens on the first request, and any subsequent request if I modify the code of that api route and refreshes the module in dev mode.

Any ideas?
Answered by Amorph
@Keyhole wasp have you tried returning nextresponse instead of response?
View full answer

13 Replies

Avatar
Keyhole waspOP
more context:
TypeError: Response body object should not be disturbed or locked
    at extractBody (node:internal/deps/undici/undici:5312:17)
    at new Request (node:internal/deps/undici/undici:9492:48)
    at new NextRequest
Avatar
@Keyhole wasp have you tried returning nextresponse instead of response?
Answer
Avatar
Keyhole waspOP
i have not, im actually new to api routes is there a guide somewhere that goes over all this concisely?
Avatar
not sure if there is but i was just reading answers from the github discussion about this error
Avatar
Keyhole waspOP
yeah that was to do with using DELETE
NextResponse may have fixed it
Avatar
yes, the first post is about delete but the answers are about post too
Avatar
Keyhole waspOP
heh this issue is all over the place, it seems to give that error for a number of reasons
Avatar
so you not getting the error anymore?
Avatar
Keyhole waspOP
i dont htink so, let me doublecheck
yeah i wanna say its fixed. thanks.