How to return API response status in NextJS13?
Asked Answered
G

3

23

Right now am using different ways to return API HTTP status in my NextJS-13 but nothing seems to be working for me.

Note: I am using Typescript in my project.

Here is my code with static 200 API response and am sending API status in body:

type postProps = {
  title: string;
  content?: string;
  published: boolean;
};

export async function POST(request: Request) {
  const post: postProps = await request.json();
  if (!post.title) {
    return NextResponse.json({
      status: 400,
      message: "Please enter title",
    });
  }
}

I have tried

import type { NextApiRequest, NextApiResponse } from "next";

export async function POST(response: NextApiResponse, request: NextApiRequest ) {
  const post: postProps = await request.body;
  if (!post.title) {
    return response.status(400).json({
     message: "Please enter title"
    })
  }
}

But it give me TypeError: res.status is not a function

I also have tried

import type { NextApiRequest, NextApiResponse } from "next";

export async function POST(response: Response, request: Request) {
  const post: postProps = await request.json();
  if (!post.title) {
    return response.status(400).json({
     message: "Please enter title"
    })
  }
}

But it give me the following error: This expression is not callable. Type 'Number' has no call signatures.

Gervase answered 24/3, 2023 at 16:1 Comment(0)
O
50

import { NextResponse } from "next/server";

NextResponse.json({
  message: "Please enter title"
}, {
  status: 400,
})
Oppenheimer answered 26/3, 2023 at 19:1 Comment(3)
How to set status: 204? Got error.Hutner
Anyone from future may check this link to handle 204 error from nextjs doc, nextjs.org/docs/messages/invalid-api-status-bodyAlbumen
source reference: developer.mozilla.org/en-US/docs/Web/API/Response/…Explain
N
0

you could easy access to the global object Response and do it like this:

export default function Post(req: NextApiRequest) {


  return Response.json({
    message: "anything"
  }, {
    status: 200
  })
}
Nicobarese answered 26/12, 2023 at 0:44 Comment(0)
S
-3

I think you mixed up the order of the request and response parameters:

export default function handler(req, res) {
  res.status(200).json({ name: 'John Doe' })
}

request should be first and response second. You're trying to access status on the request which doesn't have it.

Stoush answered 24/3, 2023 at 16:21 Comment(2)
Giving me same error with your order too. export async function POST(request: NextApiRequest, response: NextApiResponse) { const post: postProps = await request.body; if (!post.title) { return response.status(400).json({ message: "Please enter title", }); }Gervase
this example worked only for nextjs version < 13Glyn

© 2022 - 2024 — McMap. All rights reserved.