reactjstypescriptnext.js

Trying to hit an API on production fails, 404


I'm trying to deploy my web site and when I'm deploying it the API call is not being made.

It says 404 not found.

This is my project structure:

structure of my page.

I tried doing npm run build

This is my next.config.ts:

/** @type {import('next').NextConfig} */
const nextConfig = {
  distDir: "build",
  output: "export",
};

module.exports = nextConfig;

This is what it shows on console after finishing the build:

Creating an optimized production build ...
 ✓ Compiled successfully
 ✓ Linting and checking validity of types    
 ✓ Collecting page data    
 ✓ Generating static pages (7/7)
 ✓ Collecting build traces    
 ✓ Finalizing page optimization    

Route (app)                              Size     First Load JS
┌ ○ /                                    253 B           181 kB
├ ○ /_not-found                          875 B          88.1 kB
├ ƒ /api/contact                         0 B                0 B
└ ○ /contact                             23.1 kB         204 kB
+ First Load JS shared by all            87.2 kB
  ├ chunks/23-f0f016e5e82b4186.js        31.6 kB
  ├ chunks/fd9d1056-ebc592d1260611cd.js  53.7 kB
  └ other shared chunks (total)          1.95 kB


○  (Static)   prerendered as static content
ƒ  (Dynamic)  server-rendered on demand
enter code here

This is how I'm hitting the API:

 const onSubmit = async (data: ContactFormType) => {
    try {
      const response = await fetch("/api/contact", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(data),
      });

      if (response.ok) {
        reset();
      } else {
        setError(true);
      }
    } catch (error) {
      console.error("Error:", error);
    }
  };

Locally this API works, but when building it it says 404 not found.


Solution

  • You should use a complete URL when making the fetch call. Your code shows you're just using a pathname, which likely defaults to 127.0.0.1.

    You'll need a proper path like 'https://yourdomain.com/api/contact'.