7

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.

Wali Amed
  • 73
  • 1
  • 5

2 Answers2

18
import { NextResponse } from "next/server";

NextResponse.json({
  message: "Please enter title"
}, {
  status: 400,
})
Youssouf Oumar
  • 29,373
  • 11
  • 46
  • 65
brainli
  • 204
  • 1
  • 2
-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.

matthiasgiger
  • 1,086
  • 9
  • 17
  • 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", }); } – Wali Amed Mar 24 '23 at 16:26