minsoo park
minsoo park

Reputation: 11

When using dynamic route in Next.js, the image file is getting a 404 error

I'm new to developing with Next.js.

So far I've been able to figure things out, but I'm really stumped on this one.

problem : As long as the address is not a dynamic route, the image should load fine. However, only dynamic routed addresses will fail to load the image with a 404 error.

Only image files do this!

file structure :

app

--search

----[keyword]

------page.tsx

Key code :

layout.tsx

export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    <html lang="en">
      <body className={`${inter.className} mx-60 mt-20`}>
        <Header />
        {children}
        </body>
    </html>
  )
}

Header.tsx

export default function Header() {
    return (
        <header className='flex flex-col items-center space-y-5'>
            <h1 className='text-4xl font-black'>blah blah</h1>
            <div className='text-center'>
                <p>blah blah</p>
            </div>
            <a href={'https://www.instagram.com/diggingfrogclub/'}>
                <Image 
                src="icons/instagram_icon.svg" 
                alt="instagram_icon_1"
                width={30}
                height={30}
                />
            </a>
            <Form />
        </header>
    )
}

app/search/[keyword]/page.tsx

export default function Page({ params }: {params: { keyword: string }}) {
    return (
        <>
            <h1>Search</h1>
        </>
    )
}

Additional thoughts

Image

As far as I can see, it's a problem with the "Request initiator chain".

The normal path is: http://localhost:3000/icons/instagram_icon.svg

but the image with the 404 error is a

http://localhost:3000/search/icons/instagram_icon.svg

to fetch the image.

Upvotes: 0

Views: 166

Answers (1)

Taxel
Taxel

Reputation: 4207

The way your image src is written is wrong. You wrote icons/instagram_icon.svg, which resolves relatively to the current address. Change that to /icons/instagram_icon.svg, so the src always resolves to the same filepath.

Upvotes: 0

Related Questions