最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

vercel - Why is my Next.js API route returning a 404 error in production but works locally? - Stack Overflow

programmeradmin2浏览0评论

I have a Next.js app, and I'm facing an issue where an API route works locally but returns a 404 error in production on Vercel.

Here is my setup:

I have an API route at /pages/api/shows.js that fetches shows data from a database.

The URL for this API route is hardcoded in the frontend as:

const apiUrl = ${process.env.NEXT_PUBLIC_API_LINK}/api/shows;

When I run the app locally, everything works fine. I can see the correct data being fetched.

However, in production (on Vercel), when I try to access the same route, I get a 404 error:

Error fetching shows: Error: HTTP Error: 404

Troubleshooting: I verified that NEXT_PUBLIC_API_LINK is correctly set in both local and production environments.

The API route is accessible locally at http://localhost:3000/api/shows.

On Vercel, the API route is not returning data and instead is giving a 404 error.

What I’ve tried:

  • I checked the API route on Vercel directly by opening it in the browser, and there it works. but not with the fetch.
  • I tried hardcoding the API URL directly in the fetch function, but that also doesn’t work in production. So nothings wrong with the environment variables
  • I checked my next.config.js and .env.local files for any misconfigurations, but they seem fine.

My question:

Why is the /api/shows route returning a 404 error in production on Vercel, even though it works locally?

What could be causing this issue, and how can I fix it?

app/lib/fetchShows.ts

import { Show } from "@/app/lib/types";

export const fetchShows = async (): Promise<Show[]> => {
  const apiUrl = `${process.env.NEXT_PUBLIC_API_LINK}/api/shows`;
  console.log("Fetching from API:", apiUrl); // Debug log

  try {
    const response = await fetch(apiUrl);
    if (!response.ok) throw new Error(`HTTP Error: ${response.status}`);
    return response.json();
  } catch (error) {
    console.error("Error fetching shows:", error);
    return []; // Voorkomt build failure
  }
};
发布评论

评论列表(0)

  1. 暂无评论