Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return a response from an API Route and use it on the client in the app router of Next.js

Of all the changes from Next.js 12 to 13, this is the most confusing. I have to look it up every time I want to make a fetch request because of all this JSON confusion. Can someone PLEASE help me once and for all?

I make a fetch POST request to the API handler like so:

//client component
const res = await fetch('/api/dostuff', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({dataObj: {hey: "ho"})
    })
//PLEASE HELP ME GET THE RESPONSE

I receive it like so:

//route.js in api/dostuff/
export async function POST(request) {

  const { dataObj } = await request.json()

  //PLEASE HELP ME RETURN THIS
  
}

I've tried like a hundred different variations between all the ultra-confusing json methods (JSON.stringify, JSON.parse, and the extra confusing json()), but nothing works. In Next.js 12 I didn't have to type the word "json" once.

like image 802
Yeats Avatar asked Sep 06 '25 08:09

Yeats


1 Answers

You can return plain text using the Response constructor:

// api/route.js

export async function POST(request) {
  return new Response("Hello, Next.js!", {
    status: 200,
  });
}

Or return JSON, using NextResponse from "next/server":

// api/route.js

import { NextResponse } from "next/server";

export async function POST(request) {
  return NextResponse.json({ message: "Succes" });
}

And consume the response on the client:

const res = await fetch("/api/dostuff", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
  },
  body: JSON.stringify({ dataObj: { hey: "ho" } }),
});
// For the first example (sending plain text):
const data = await res.text();
// For the second one (sending a JSON):
const data = await res.json();

For more, check out Route Handlers.

like image 118
yousoumar Avatar answered Sep 08 '25 10:09

yousoumar