reactjstypescriptnext.jsnext.js13

How to return API response status in NextJS13?


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.


Solution

  • In Next.js 13 (especially with the app directory), the way you handle API routes has slightly changed compared to previous versions. Specifically, you’re now using NextResponse instead of the res and req objects that were used in the pages directory.

    import { NextResponse } from "next/server";
    
    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(
          { message: "Please enter title" },
          { status: 400 }
        );
      }
    
      return NextResponse.json(
        { message: "Post created successfully", post },
        { status: 200 }
      );
    }