Search code examples
reactjsnext.jsvercelnextjs-image

issues with nextjs images from 3rd party


So im running into 2 issues. First im using Firebase to authorize GitHub & Google logins, so im displaying the persons avatar as a profile image in my navigation bar. Now everything is working just fine in my code until I switch <img> to <Image> - then im getting these two errors: enter image description here

enter image description here

Here is a snippet where I'm using the avatar:

import Image from 'next/image'
import { useAuth } from '@/lib/auth';
const DashboardShell = ({ children }) => {
      const { user, signout } = useAuth();
    
      return (
            <Link href="/account" passHref>
              <a>
                <Image
                  src={user?.photoUrl ?? ''}
                  width="96"
                  height="96"
                  alt="profile avatar"
                />
              </a>
            </Link>
      )
      
    }

Now when I use img instead of Image, the avatars show up and work. When I switch it to Image I get the errors, and I console.log'd the user?.photoUrl and it shows up as undefined, so I kept the console.log and switched back to img and I noticed that the console log shows undefined as soon as the page loads and then immediately logs the URL, so its logging undefined and the url.

It's almost like the next-image try's to load before the avatar URL is retrieved.

So my question is, is there is way to tell next/image to wait to load till the user?.photoUrl is retrieved/populated?

Also yes, I have image domains listed in my next.config.js file: const path = require('path')

module.exports = {
  trailingSlash: true,
  sassOptions: {
    includePaths: [path.join(__dirname, 'styles')]
  },
  images: {
    domains: ['lh3.googleusercontent.com', 'avatars.githubusercontent.com'],
  },
}

I'm on "next": "12.1.0", and I'm running on Vercel.


Solution

  • I think your image hostname problem has been solved with your latest config in next.config.js

    To fix the 2nd problem which is the undefined image on next/image. You can have a separate image source check

    import NextImage from 'next/image'
    import { useAuth } from '@/lib/auth';
    
    const Image = (props) => {
       if(props.src) {
          return <NextImage {...props}/>
       }
       
       //TODO: if the image source is not there, you can set a default source
       //const defaultSrc = "something"
    
       return <img {...props} src={defaultSrc}/>
    }
    
    const DashboardShell = ({ children }) => {
          const { user, signout } = useAuth();
    
          return (
                <Link href="/account" passHref>
                  <a>
                    <Image
                      src={user?.photoUrl}
                      width="96"
                      height="96"
                      alt="profile avatar"
                    />
                  </a>
                </Link>
          )
          
        }