Next.js Discord

Discord Forum

Help with fetch

Unanswered
robbidev posted this in #help-forum
Open in Discord
My application im working on uses MongoDB and mongoose to talk with my database. The main page soon as it runs, makes a connection with my Database to show the information. Its a dashboard afterall. It works perfectly on my my local machines. But as soon as I put my Vercel Domain, it gives me a "fetch failed" error. It uses the App router and a API route to receive the data. How do I fix this to work on Production?

My Req
async function getFryerData(id) {
    const res = await fetch(`${process.env.URL}/api/fryers`, {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
        },
        body: JSON.stringify({
            update: false,
            id: id
        }),
    })
    return res.json()
}

My API Code
import { NextResponse } from "next/server"
import Fryer from '@/models/Fryer'
import { connectDB } from '@/utils/database'

export async function POST(req, res) {
    await connectDB();
    const body = await req.json()
    if (body.update == true) {
        let fryer = await Fryer.findOneAndUpdate({ id: body.id }, { $set: { count: 1 } })
        return NextResponse.json(fryer)
    }
    console.log(body.id)
    let fryer = await Fryer.findOne({ id: body.id })
    return NextResponse.json(fryer)
}

fetch('http:localhost:3000/api/fryers') Works
fetch('https://myverceldomain.com/api/fryers') doesn't work and returns

Errors:
Vercel Build Terminal:
TypeError: fetch failed
    at Object.fetch (/vercel/path0/frontend/node_modules/next/dist/compiled/undici/index.js:1:26669)
    at processTicksAndRejections (node:internal/process/task_queues:96:5) {
  cause: Error: connect ECONNREFUSED 127.0.0.1:3000
      at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1278:16)
      at TCPConnectWrap.callbackTrampoline (node:internal/async_hooks:130:17) {
    errno: -111,
    code: 'ECONNREFUSED',
    syscall: 'connect',
    address: '127.0.0.1',
    port: 3000
  }

3 Replies

Hope this made sense
im really stumped on this and tried every idea in my head so trying to get more ideas
Golden-winged Warbler
is the build trying to hit the API (because of static gen) before the server is running?