Reputation: 23060
I'm using Next.js 14.2.3 and trying to fetch the /api/tmp
API route from the chat.tsx
component, but the error 404 is thrown even though I use route.ts
. Why?
EDIT: Is it because chat.tsx
is a client component? If yes, how can I fetch an API route in a client-side component?
chat.tsx
:
"use client";
export default function Chat() {
/.../
const test = await fetch("/api/tmp", {
method: "GET",
});
/.../
}
route.ts
:
import { NextResponse } from "next/server";
export async function GET(request: any) {
return NextResponse.json({ message: "Hello World" }, { status: 200 });
}
Structure:
src
|__app
|__components
| |__chat.tsx
|__hooks
|__pages
| |__api
| |__tmp
| |__route.ts
|__shared
|__styles
|__types
|__layout.tsx
|__page.tsx
Terminal:
GET /api/tmp 404 in 61ms
Upvotes: 0
Views: 1002
Reputation: 1387
Problem :
Fetching Next.js 14 API route throws a 404 error even though I use route.ts
Cause :
Improper URL
Solution :
/pages/api/tmp
/api/tmp
causes NextJS to look under app/api/tmp
thats why it gives you 404/api/tmp
then just keep api folder under app (app/api
).Read More :
Route Handlers : https://nextjs.org/docs/app/building-your-application/routing/route-handlers
Creating Routes : https://nextjs.org/docs/app/building-your-application/routing/defining-routes#creating-routes
If you have any doubts, then please leave a comment (I will update answer if necessary)
Upvotes: 0