useEffect(() => {
const fetchAnalysisData = async () => {
console.log(“Starting to fetch analysis data…”);
const response = await fetch(“/api/get-final-result”);
try {
if (!response.ok) {
throw new Error(“Failed to fetch analysis data”);
}
It is the codes in app/analysis/page.tsx and from here it request the api to app/api/get-final-result/route.ts
But it could not find the path. It is giving 404 error. It is on local right now. I am not sure that why it could not find the file path. There is another api files in api folers, but another works well.
app
|—analysis/page.tsx
|—api
|—get-final-result/route.ts → It does not work when I call it from analysis/page.tsx
|—saveFilePath/route.ts → It does work when I call it from app/page.tsx
|—page.tsx
next.js version is 14.
Do I need to change the api directory?
Deployment URL or Custom Domain:
Environment (local, preview, production):
Project Framework:
Build Settings:
Framework Preset:
Build Command (if not default):
Output Directory (if not default):
Install Command (if not default):
Node/Runtime Version:
Package Manager:
Relevant Packages:
Thank you for sharing your project structure and the issue you’re facing!
Your API route structure (app/api/get-final-result/route.ts) looks correct for Next.js 14 with the App Router. Make sure the file is named exactly route.ts within the get-final-result folder.
Make sure that app/api/get-final-result/route.ts is correctly implemented:
import { NextResponse } from 'next/server'
export async function GET() {
// Your logic here
return NextResponse.json({ message: 'This is the final result' })
}
In Next.js 14 with the App Router, we should use Server Components for data fetching whenever possible . Here’s how you should structure your app/analysis/page.tsx:
import { headers } from 'next/headers'
async function getData() {
const res = await fetch('http://localhost:3000/api/get-final-result', {
headers: headers(),
})
if (!res.ok) {
throw new Error('Failed to fetch data')
}
return res.json()
}
export default async function Page() {
const data = await getData()
return (
<main>
<h1>Analysis Page</h1>
<pre>{JSON.stringify(data, null, 2)}</pre>
</main>
)
}
This approach uses a Server Component, which is preferred for data fetching in Next.js 14 .
If you’re still getting a 404 error, it could be due to a few reasons:
Ensure there are no typos in the file or folder names.
Check for any conflicting route definitions.
Look for any middleware (middleware.ts in your app directory) that might be interfering with specific routes.
If the issue persists, try clearing the .next cache and rebuilding:
rm -rf .next
npm run build
npm run dev
Remember, in Next.js 14 with the App Router, API routes should work out of the box without needing to change the API directory . The structure you have (app/api/get-final-result/route.ts) is correct according to the Next.js documentation.