Reputation: 133
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
Upvotes: 3
Views: 7873
Reputation: 201
You need to set your .env variable with prefix NEXT_PUBLIC
like for example:
NEXT_PUBLIC_API_URL=http://localhost:3000
You got errors in production mode because if you directly set it as API_URL=http://localhost:3000
, Next.js assumes that this is a secret variable therefore it can't make a request from client-side.
Upvotes: 0
Reputation: 1
It seems that fetch
works differently in each and every "Runtime".
So, it might help to change the runtime.
Here's the link to Vercel's docs
Upvotes: 0
Reputation: 21
in next.config.js
write env:{}
https://nextjs.org/docs/pages/api-reference/next-config-js/env
for exp.
env: { API_URL: "https://yours-project.vercel.app"} and use this API_URL in fetch
const apiUrl = process.env.API_URL;
const res = await fetch(`${apiUrl}/api/jobs`, {
cache: "no-store",
});
it helped me.
Upvotes: 2
Reputation: 36
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.
Upvotes: 2