Search code examples
dockernext.jsserver-side-rendering

Nextjs: docker build can't fetch my local API in App router for serverside component when built


I am using APP route, I have a serverside component which fetches URL from my API: http://localhost/api/image, and load it in <Image>, it works well in local, but when I run docker build, it seems that docker has a hard time fetching my API when building. Any idea?

My API route located at /app/api/fetch-image

import {NextResponse} from 'next/server'
import {getDownloadURL, ref} from "firebase/storage";
import {storage} from "@/firebase/storage";

export async function GET(Request) {
    const url = new URL(Request.url)
    const path = url.searchParams.get("path")
    const image_url = await getDownloadURL(ref(storage, path))
    return NextResponse.json({data: image_url}, {status: 200})
}

The code that call this API to fetch image URL:

async function fetchSingleImage(path) {
    let param = new URLSearchParams()
    param.append("path", path)
    const res = await fetch('http://localhost:3001/api/fetch-image?' + param.toString())
    const image_data = await res.json()
    return image_data["data"]
}

When I run docker build --platform linux/amd64 -t hotel-la-roche-pleureuse:20230821v2, I have the error

226.1 Error occurred prerendering page "/". Read more: https://nextjs.org/docs/messages/prerender-error
226.1 TypeError: fetch failed
226.1     at Object.fetch (node:internal/deps/undici/undici:11576:11)
226.1     at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
226.1 - info Generating static pages (11/11)
226.1 
226.1 > Export encountered errors on following paths:
226.1   /page: /
226.1   /photos/page: /photos
226.3 error Command failed with exit code 1.
226.3 info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

I am having a dockerfile but not docker-compile, I have searched but nothing online.

It works totally fine in local development when I use yarn dev, and I have built it multiple times using the docker build command so I suspect it is because when I use docker build, the API is not available or something, but I am just lack of experience of how to fix that.


Solution

  • I've discovered a workaround. To avoid errors during the docker build, I return some random valid data to my server-side code. Once I run the command, the API first reaches out to the server. Afterwards, I utilize the API on my server to retrieve data. Consequently, I remove the placeholder data and directly fetch from the API on my server.

    Still looking for a better solution because I am sure that's not the most correct way.