I am developing an app in NextJs 14.2.5.
I am encountering an issue when I make a POST using fetch; the server returns the correct response with a 200 status.
I have tested this on Postman as well and that works fine.
But the fetch call on the client throws a Fetch failed error.
Client code (page.tsx)
'use client'
import Link from "next/link";
import { Button } from "react-bootstrap";
// export const dynamic = "force-dynamic";
// export const fetchCache = "force-no-store";
export default function Home() {
const handleLoginClick = async () => {
try {
alert("fetch before");
const response = await fetch('/api/auth/req', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ address: 'TQEy5ZbcTZrctHJufE47E9hHzPfvT8SRcE' }),
});
alert("fetch after"); // never reaches this line
const resJson = await response.json();
} catch (error) {
console.error(error);//Always reaches here; server has returned 200
}
}
return (
<main>
<div className="App">
<Button className="nav-link text-white" onClick={handleLoginClick} href="/">Login</Button>
</div>
</main>
)
}
My API route
// app/api/auth/req/route.js
import { NextResponse } from "next/server";
import dbConnect from "@/lib/dbConnect";
import User from "../../../../models/user";
export async function POST(request, res) {
try {
let reqJson = await request.json();
let address = reqJson.address;
if(!address || !address.length){
return NextResponse.json({nonce_ : null, msg : 'Address not sent with request'}, { status: 500 });
}
console.log(address);
await dbConnect();
let nonce = "somenonce";
const updatedUser = await User.findOneAndUpdate(
{ address: address },
{ nonce: nonce },
{ new: true }
);
if (updatedUser) {
console.log('Nonce updated successfully:', updatedUser);
return NextResponse.json({ nonce_: nonce }, { status: 200 });
} else {
console.log('User not found with the given address.');
return NextResponse.json({nonce_ : null, msg : 'User not found with the given address.'}, { status: 500 });
}
} catch (error) {
console.log(error);
console.log("fail");
}
return NextResponse.json({nonce_ : null}, { status: 500 });
}
Why is the client failing with this error?
And how should i fix it?
Here is what i have tried
- As per this post
https://stackoverflow.com/questions/57477805/why-do-i-get-fetch-failed-loading-when-it-actually-worked
- I have attempted to send a 204 status; no luck 204 is not recognized
- The NextResponse has a body (nonce_ : nonce); still no luck
-
I am assuming that cors handling works out of the box in Nextjs. So I havent done anything to handle that.
-
As per this blog
https://medium.com/phantom3/next-js-14-build-prerender-error-fix-f3c51de2fe1d
I have also set the following in the client; this didnt work either
export const dynamic = "force-dynamic";
export const fetchCache = "force-no-store";
- I checked – on the server the code executes in very less time – about 151 ms. Just in case there maybe a delay on the server side.
Solution
Thanks to Phils suggestion below I simply removed the href attribute from the button and all worked correctly.