Rok Benko
Rok Benko

Reputation: 23060

Fetching Next.js 14 API route throws a 404 error even though I use route.ts

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

Answers (1)

Beast80K
Beast80K

Reputation: 1387

Problem :

Fetching Next.js 14 API route throws a 404 error even though I use route.ts

Cause :

Improper URL

Solution :

  • NextJS is file-system based router where folders are used to define routes
  • NextJS uses folder name as URL hence, Change URL to /pages/api/tmp
  • /api/tmp causes NextJS to look under app/api/tmp thats why it gives you 404
  • If you want URL to be /api/tmp then just keep api folder under app (app/api).

Read More :

If you have any doubts, then please leave a comment (I will update answer if necessary)

Upvotes: 0

Related Questions