can not load image from public folder in next14

26 Views Asked by At

the code worked fine until i introduced a middleware file

src/middleware.ts

import { NextRequest, NextResponse } from 'next/server'

export const config = {
  matcher: [
    /*
     * Match all request paths except for the ones starting with:
     * - api (API routes)
     * - _next/static (static files)
     * - _next/image (image optimization files)
     * - favicon.ico (favicon file)
     */
    '/((?!api|_next/static|_next/image|favicon.ico).*)',
  ],
}

export default async function middleware(req: NextRequest) {
  const url = req.nextUrl

  // Get hostname of request (e.g. demo.vercel.pub, demo.localhost:3000)
  let hostname = req.headers
    .get('host')!
    .replace('.localhost:3000', `.${process.env.NEXT_PUBLIC_ROOT_DOMAIN}`)

  const searchParams = req.nextUrl.searchParams.toString()
  // Get the pathname of the request (e.g. /, /about, /blog/first-post)
  const path = `${url.pathname}${
    searchParams.length > 0 ? `?${searchParams}` : ''
  }`

  // rewrites for app pages
  if (hostname == `help.${process.env.NEXT_PUBLIC_ROOT_DOMAIN}`) {
    return NextResponse.rewrite(
      new URL(`/help${path === '' ? '' : path}`, req.url),
    )
  }

  // rewrite root application to `/` folder
  if (
    hostname === 'localhost:3000' ||
    hostname === process.env.NEXT_PUBLIC_ROOT_DOMAIN
  ) {
    return NextResponse.rewrite(new URL(`${path === '/' ? '' : path}`, req.url))
  }
}

src/app/help/component

import Image from 'next/image'

import React from 'react'



const Topic = () => {

  return (
    
        <div className="relative w-12 h-12 bg-slate-50">
          <Image
            src={'/public/icons/handshake_icon.png'}
            alt={props.topicName}
            fill={true}
          />
      
      </div>
    
  )
}

export default Topic

produces The requested resource isn't a valid image for /public/icons/handshake_icon.png received text/html; charset=utf-8 , the code used to work before adding the middleware function can you please fix it?

1

There are 1 best solutions below

0
bhavik-civica On

Try to load your image without the public in the file path as below.

<Image src={'/icons/handshake_icon.png'} alt={props.topicName} fill={true} />

Files inside the public can then be referenced by your code starting from the base URL (/)

For example, the file public/avatars/me.png can be viewed by visiting the /avatars/me.png path.

Refer to Doc for more details: https://nextjs.org/docs/app/building-your-application/optimizing/static-assets