Search code examples
error-handlingpublicnext.js13nextjs-image

The images do not work with a tutorial to follow to make my page in nextjs with i18n, can someone help me?


Everything works great translate everything in nextjs13.4, tailwindcss and i18n, I'm not using typescript, but my image doesn't load anywhere despite being in the public folder.

Error that I get in the console: GET http://localhost:3000/_next/image?url=%2Fimagentest.jpg&w=128&q=75 400 (Bad Request)

Guide: https://locize.com/blog/next-13-app-dir-i18n/

I hope you help me how to fix this code error


Solution

  • this working for me:

    add the const PUBLIC_FILE and add one "if" with them :

    import { NextResponse } from 'next/server'
    import acceptLanguage from 'accept-language'
    import { fallbackLng, languages } from './app/i18n/settings'
    
    acceptLanguage.languages(languages)
    const PUBLIC_FILE = /\.(.*)$/
     
    export const config = {
      matcher: ['/((?!api|_next/static|_next/public|_next/image|assets|favicon.ico|sw.js).*)']
    }
    
    
    const cookieName = 'i18next'
    
    export function middleware(req) { 
    
      let lng
      if (req.cookies.has(cookieName)) lng = acceptLanguage.get(req.cookies.get(cookieName).value)
      if (!lng) lng = acceptLanguage.get(req.headers.get('Accept-Language'))
      if (!lng) lng = fallbackLng
    
      //to take the files from the publisc folder
      if (    
        PUBLIC_FILE.test(req.nextUrl.pathname)
      ) {
        return
      }  
    
      // Redirect if lng in path is not supported
      if (
        !languages.some(loc => req.nextUrl.pathname.startsWith(`/${loc}`)) &&
        !req.nextUrl.pathname.startsWith('/_next') 
      ) {
        return NextResponse.redirect(new URL(`/${lng}${req.nextUrl.pathname}`, req.url))
      }
    
      if (req.headers.has('referer')) {
        const refererUrl = new URL(req.headers.get('referer'))
        const lngInReferer = languages.find((l) => refererUrl.pathname.startsWith(`/${l}`))
        const response = NextResponse.next()
        if (lngInReferer) response.cookies.set(cookieName, lngInReferer)
        return response
      }
    
      return NextResponse.next()
    }