I'm building a website using next.js
which uses Route Handlers
. When I run the npm run build
command it works perfectly fine, but when I deploy to Vercel it shows this error:
TypeError: fetch failed at Object.fetch (node:internal/deps/undici/undici:11457:11) at process.processTicksAndRejections (node:internal/process/task_queues:95:5) { cause: Error: connect ECONNREFUSED 127.0.0.1:3000 at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1494:16) at TCPConnectWrap.callbackTrampoline (node:internal/async_hooks:130:17) { errno: -111, code: 'ECONNREFUSED', syscall: 'connect', address: '127.0.0.1', port: 3000 } }
Error: Command "npm run build" exited with 1
Can someone tell me where the issue is? There no errors in the browser console, nor in the build command. Here is my code:
import React from 'react'
import { Search } from '@/components'
async function getJobs() {
const res = await fetch('http://localhost:3000/api/jobs');
if (!res.ok) {
throw new Error("Couldn't fetch")
}
const data = await res.json();
return data;
}
export default async function Home() {
const jobs = await getJobs();
return (
<main className='px-6 md:px-8'>
<Search />
<pre>{ JSON.stringify(jobs, null, 2)}</pre>
<span>{new Date().getTime()}</span>
</main>
)
}
export const revalidate = 900;
Any help is appreciated. If you need more information about this problem, feel free to ask. Thanks in advance
To solve that, add a .env file at the project root with an enviroment variable receiveing the 'http://localhost:3000' value, then import to your fetch url by using ${process.env.NAME_OF_YOUR_ENV_VARIABLE}/api/jobs
. then go to your dashboard in vercel and set the value of NAME_OF_YOUR_ENV_VARIABLE as the base url of the deploy gave by vercel.