I am encountering an issue with calling my route API (404) in my new nextjs project.
The route API can be found at src/app/api/speed.js
Within my page src/app/page.tsx, I have the following code snippet:
fetch("api/speed").then(res=>res.json).then(data=>alert(data.message))
Despite this, I consistently receive a 404 error on GET http://localhost:3000/api/speed when checking the network devtools tab.
The content of src/app/api/speed.js is as follows:
export default function handler (_req,res) {
res.status(200).json({ message: "hey" })
}
In src/app/page.tsx:
'use clients;
export default function Home() {
function handleClick() {
fetch("api/speed").then(res=>res.json.then(({message})=>alert(message))
}
return (
<><main><div onClick={handleClick}>HEY</div></main><>
)
}
Note: The API route functions correctly if moved to src/app/api/speed/route.js. However, based on the documentation example of pages/api/hello.js, it should work in the original location.
Note 2: In addition to relocating the API route, I also had to make adjustments to the code. The provided example in the official documentation was not functional (possibly deprecated). Here is the updated code:
import {NextResponse} from "next/server";
export async function GET(req) {
return NextResponse.json({message: "hey"})
}
What could be causing this issue?