Unverified Commit cdb0c474 authored by Steven's avatar Steven Committed by GitHub

Improve `next/image` error message when `src` prop is missing (#38847)

Currently, when a user forgets the `src` prop on an image, an error is thrown. However that error doesn't include any of the the user's code in the stack trace, so its nearly impossible to figure out which image is the culprit if there are multiple images on the page.

Since this error only throws on demand when a page is visited during `next dev`, we can instead delay the error so it no longer prints on the server but prints on mount instead. At that point, we'll have the `<img>` element via ref and can print it to the web console with the stack trace.

- Fixes #23742 
parent 672bdaee
...@@ -357,10 +357,6 @@ export default function Image({ ...@@ -357,10 +357,6 @@ export default function Image({
} }
src = typeof src === 'string' ? src : staticSrc src = typeof src === 'string' ? src : staticSrc
const widthInt = getInt(width)
const heightInt = getInt(height)
const qualityInt = getInt(quality)
let isLazy = let isLazy =
!priority && (loading === 'lazy' || typeof loading === 'undefined') !priority && (loading === 'lazy' || typeof loading === 'undefined')
if (src.startsWith('data:') || src.startsWith('blob:')) { if (src.startsWith('data:') || src.startsWith('blob:')) {
...@@ -373,136 +369,139 @@ export default function Image({ ...@@ -373,136 +369,139 @@ export default function Image({
} }
const [blurComplete, setBlurComplete] = useState(false) const [blurComplete, setBlurComplete] = useState(false)
let widthInt = getInt(width)
let heightInt = getInt(height)
const qualityInt = getInt(quality)
if (process.env.NODE_ENV !== 'production') { if (process.env.NODE_ENV !== 'production') {
if (!src) { if (!src) {
throw new Error( // React doesn't show the stack trace and there's
`Image is missing required "src" property. Make sure you pass "src" in props to the \`next/image\` component. Received: ${JSON.stringify( // no `src` to help identify which image, so we
{ width, height, quality } // instead console.error(ref) during mount.
)}` unoptimized = true
) } else {
} if (typeof widthInt === 'undefined') {
if (typeof widthInt === 'undefined') { throw new Error(
throw new Error( `Image with src "${src}" is missing required "width" property.`
`Image with src "${src}" is missing required "width" property.` )
) } else if (isNaN(widthInt)) {
} else if (isNaN(widthInt)) { throw new Error(
throw new Error( `Image with src "${src}" has invalid "width" property. Expected a numeric value in pixels but received "${width}".`
`Image with src "${src}" has invalid "width" property. Expected a numeric value in pixels but received "${width}".` )
) }
} if (typeof heightInt === 'undefined') {
if (typeof heightInt === 'undefined') { throw new Error(
throw new Error( `Image with src "${src}" is missing required "height" property.`
`Image with src "${src}" is missing required "height" property.` )
) } else if (isNaN(heightInt)) {
} else if (isNaN(heightInt)) { throw new Error(
throw new Error( `Image with src "${src}" has invalid "height" property. Expected a numeric value in pixels but received "${height}".`
`Image with src "${src}" has invalid "height" property. Expected a numeric value in pixels but received "${height}".` )
) }
} if (!VALID_LOADING_VALUES.includes(loading)) {
if (!VALID_LOADING_VALUES.includes(loading)) { throw new Error(
throw new Error( `Image with src "${src}" has invalid "loading" property. Provided "${loading}" should be one of ${VALID_LOADING_VALUES.map(
`Image with src "${src}" has invalid "loading" property. Provided "${loading}" should be one of ${VALID_LOADING_VALUES.map( String
String ).join(',')}.`
).join(',')}.` )
) }
} if (priority && loading === 'lazy') {
if (priority && loading === 'lazy') { throw new Error(
throw new Error( `Image with src "${src}" has both "priority" and "loading='lazy'" properties. Only one should be used.`
`Image with src "${src}" has both "priority" and "loading='lazy'" properties. Only one should be used.`
)
}
if ('objectFit' in rest) {
throw new Error(
`Image with src "${src}" has unknown prop "objectFit". This style should be specified using the "style" attribute.`
)
}
if ('objectPosition' in rest) {
throw new Error(
`Image with src "${src}" has unknown prop "objectPosition". This style should be specified using the "style" attribute.`
)
}
if (placeholder === 'blur') {
if ((widthInt || 0) * (heightInt || 0) < 1600) {
warnOnce(
`Image with src "${src}" is smaller than 40x40. Consider removing the "placeholder='blur'" property to improve performance.`
) )
} }
if (!blurDataURL) {
const VALID_BLUR_EXT = ['jpeg', 'png', 'webp', 'avif'] // should match next-image-loader
if ('objectFit' in rest) {
throw new Error( throw new Error(
`Image with src "${src}" has "placeholder='blur'" property but is missing the "blurDataURL" property. `Image with src "${src}" has unknown prop "objectFit". This style should be specified using the "style" attribute.`
Possible solutions: )
- Add a "blurDataURL" property, the contents should be a small Data URL to represent the image }
- Change the "src" property to a static import with one of the supported file types: ${VALID_BLUR_EXT.join( if ('objectPosition' in rest) {
',' throw new Error(
)} `Image with src "${src}" has unknown prop "objectPosition". This style should be specified using the "style" attribute.`
- Remove the "placeholder" property, effectively no blur effect
Read more: https://nextjs.org/docs/messages/placeholder-blur-data-url`
) )
} }
}
if ('ref' in rest) {
warnOnce(
`Image with src "${src}" is using unsupported "ref" property. Consider using the "onLoadingComplete" property instead.`
)
}
if (!unoptimized && loader !== defaultLoader) { if (placeholder === 'blur') {
const urlStr = loader({ if ((widthInt || 0) * (heightInt || 0) < 1600) {
config, warnOnce(
src, `Image with src "${src}" is smaller than 40x40. Consider removing the "placeholder='blur'" property to improve performance.`
width: widthInt || 400, )
quality: qualityInt || 75, }
}) if (!blurDataURL) {
let url: URL | undefined const VALID_BLUR_EXT = ['jpeg', 'png', 'webp', 'avif'] // should match next-image-loader
try {
url = new URL(urlStr) throw new Error(
} catch (err) {} `Image with src "${src}" has "placeholder='blur'" property but is missing the "blurDataURL" property.
if (urlStr === src || (url && url.pathname === src && !url.search)) { Possible solutions:
- Add a "blurDataURL" property, the contents should be a small Data URL to represent the image
- Change the "src" property to a static import with one of the supported file types: ${VALID_BLUR_EXT.join(
','
)}
- Remove the "placeholder" property, effectively no blur effect
Read more: https://nextjs.org/docs/messages/placeholder-blur-data-url`
)
}
}
if ('ref' in rest) {
warnOnce( warnOnce(
`Image with src "${src}" has a "loader" property that does not implement width. Please implement it or use the "unoptimized" property instead.` + `Image with src "${src}" is using unsupported "ref" property. Consider using the "onLoadingComplete" property instead.`
`\nRead more: https://nextjs.org/docs/messages/next-image-missing-loader-width`
) )
} }
}
if ( if (!unoptimized && loader !== defaultLoader) {
typeof window !== 'undefined' && const urlStr = loader({
!perfObserver && config,
window.PerformanceObserver src,
) { width: widthInt || 400,
perfObserver = new PerformanceObserver((entryList) => { quality: qualityInt || 75,
for (const entry of entryList.getEntries()) { })
// @ts-ignore - missing "LargestContentfulPaint" class with "element" prop let url: URL | undefined
const imgSrc = entry?.element?.src || '' try {
const lcpImage = allImgs.get(imgSrc) url = new URL(urlStr)
if ( } catch (err) {}
lcpImage && if (urlStr === src || (url && url.pathname === src && !url.search)) {
!lcpImage.priority && warnOnce(
lcpImage.placeholder !== 'blur' && `Image with src "${src}" has a "loader" property that does not implement width. Please implement it or use the "unoptimized" property instead.` +
!lcpImage.src.startsWith('data:') && `\nRead more: https://nextjs.org/docs/messages/next-image-missing-loader-width`
!lcpImage.src.startsWith('blob:') )
) {
// https://web.dev/lcp/#measure-lcp-in-javascript
warnOnce(
`Image with src "${lcpImage.src}" was detected as the Largest Contentful Paint (LCP). Please add the "priority" property if this image is above the fold.` +
`\nRead more: https://nextjs.org/docs/api-reference/next/image#priority`
)
}
} }
}) }
try {
perfObserver.observe({ if (
type: 'largest-contentful-paint', typeof window !== 'undefined' &&
buffered: true, !perfObserver &&
window.PerformanceObserver
) {
perfObserver = new PerformanceObserver((entryList) => {
for (const entry of entryList.getEntries()) {
// @ts-ignore - missing "LargestContentfulPaint" class with "element" prop
const imgSrc = entry?.element?.src || ''
const lcpImage = allImgs.get(imgSrc)
if (
lcpImage &&
!lcpImage.priority &&
lcpImage.placeholder !== 'blur' &&
!lcpImage.src.startsWith('data:') &&
!lcpImage.src.startsWith('blob:')
) {
// https://web.dev/lcp/#measure-lcp-in-javascript
warnOnce(
`Image with src "${lcpImage.src}" was detected as the Largest Contentful Paint (LCP). Please add the "priority" property if this image is above the fold.` +
`\nRead more: https://nextjs.org/docs/api-reference/next/image#priority`
)
}
}
}) })
} catch (err) { try {
// Log error but don't crash the app perfObserver.observe({
console.error(err) type: 'largest-contentful-paint',
buffered: true,
})
} catch (err) {
// Log error but don't crash the app
console.error(err)
}
} }
} }
} }
...@@ -652,6 +651,11 @@ const ImageElement = ({ ...@@ -652,6 +651,11 @@ const ImageElement = ({
style={{ ...imgStyle, ...blurStyle }} style={{ ...imgStyle, ...blurStyle }}
ref={useCallback( ref={useCallback(
(img: ImgElementWithDataProp) => { (img: ImgElementWithDataProp) => {
if (process.env.NODE_ENV !== 'production') {
if (img && !srcString) {
console.error(`Image is missing required "src" property:`, img)
}
}
if (img?.complete) { if (img?.complete) {
handleLoading( handleLoading(
img, img,
......
...@@ -429,10 +429,6 @@ export default function Image({ ...@@ -429,10 +429,6 @@ export default function Image({
} }
src = typeof src === 'string' ? src : staticSrc src = typeof src === 'string' ? src : staticSrc
const widthInt = getInt(width)
const heightInt = getInt(height)
const qualityInt = getInt(quality)
let isLazy = let isLazy =
!priority && (loading === 'lazy' || typeof loading === 'undefined') !priority && (loading === 'lazy' || typeof loading === 'undefined')
if (src.startsWith('data:') || src.startsWith('blob:')) { if (src.startsWith('data:') || src.startsWith('blob:')) {
...@@ -505,68 +501,73 @@ export default function Image({ ...@@ -505,68 +501,73 @@ export default function Image({
objectPosition, objectPosition,
} }
let widthInt = getInt(width)
let heightInt = getInt(height)
const qualityInt = getInt(quality)
if (process.env.NODE_ENV !== 'production') { if (process.env.NODE_ENV !== 'production') {
if (!src) { if (!src) {
throw new Error( // React doesn't show the stack trace and there's
`Image is missing required "src" property. Make sure you pass "src" in props to the \`next/image\` component. Received: ${JSON.stringify( // no `src` to help identify which image, so we
{ width, height, quality } // instead console.error(ref) during mount.
)}` widthInt = widthInt || 1
) heightInt = heightInt || 1
} unoptimized = true
if (!VALID_LAYOUT_VALUES.includes(layout)) { } else {
if ((layout as any) === 'raw') { if (!VALID_LAYOUT_VALUES.includes(layout)) {
if ((layout as any) === 'raw') {
throw new Error(
`The layout="raw" experiment has been moved to a new module. Please import \`next/future/image\` instead.`
)
}
throw new Error( throw new Error(
`The layout="raw" experiment has been moved to a new module. Please import \`next/future/image\` instead.` `Image with src "${src}" has invalid "layout" property. Provided "${layout}" should be one of ${VALID_LAYOUT_VALUES.map(
String
).join(',')}.`
) )
} }
throw new Error(
`Image with src "${src}" has invalid "layout" property. Provided "${layout}" should be one of ${VALID_LAYOUT_VALUES.map(
String
).join(',')}.`
)
}
if ( if (
(typeof widthInt !== 'undefined' && isNaN(widthInt)) || (typeof widthInt !== 'undefined' && isNaN(widthInt)) ||
(typeof heightInt !== 'undefined' && isNaN(heightInt)) (typeof heightInt !== 'undefined' && isNaN(heightInt))
) { ) {
throw new Error( throw new Error(
`Image with src "${src}" has invalid "width" or "height" property. These should be numeric values.` `Image with src "${src}" has invalid "width" or "height" property. These should be numeric values.`
) )
} }
if (layout === 'fill' && (width || height)) { if (layout === 'fill' && (width || height)) {
warnOnce(
`Image with src "${src}" and "layout='fill'" has unused properties assigned. Please remove "width" and "height".`
)
}
if (!VALID_LOADING_VALUES.includes(loading)) {
throw new Error(
`Image with src "${src}" has invalid "loading" property. Provided "${loading}" should be one of ${VALID_LOADING_VALUES.map(
String
).join(',')}.`
)
}
if (priority && loading === 'lazy') {
throw new Error(
`Image with src "${src}" has both "priority" and "loading='lazy'" properties. Only one should be used.`
)
}
if (sizes && layout !== 'fill' && layout !== 'responsive') {
warnOnce(
`Image with src "${src}" has "sizes" property but it will be ignored. Only use "sizes" with "layout='fill'" or "layout='responsive'"`
)
}
if (placeholder === 'blur') {
if (layout !== 'fill' && (widthInt || 0) * (heightInt || 0) < 1600) {
warnOnce( warnOnce(
`Image with src "${src}" is smaller than 40x40. Consider removing the "placeholder='blur'" property to improve performance.` `Image with src "${src}" and "layout='fill'" has unused properties assigned. Please remove "width" and "height".`
) )
} }
if (!blurDataURL) { if (!VALID_LOADING_VALUES.includes(loading)) {
const VALID_BLUR_EXT = ['jpeg', 'png', 'webp', 'avif'] // should match next-image-loader throw new Error(
`Image with src "${src}" has invalid "loading" property. Provided "${loading}" should be one of ${VALID_LOADING_VALUES.map(
String
).join(',')}.`
)
}
if (priority && loading === 'lazy') {
throw new Error( throw new Error(
`Image with src "${src}" has "placeholder='blur'" property but is missing the "blurDataURL" property. `Image with src "${src}" has both "priority" and "loading='lazy'" properties. Only one should be used.`
)
}
if (sizes && layout !== 'fill' && layout !== 'responsive') {
warnOnce(
`Image with src "${src}" has "sizes" property but it will be ignored. Only use "sizes" with "layout='fill'" or "layout='responsive'"`
)
}
if (placeholder === 'blur') {
if (layout !== 'fill' && (widthInt || 0) * (heightInt || 0) < 1600) {
warnOnce(
`Image with src "${src}" is smaller than 40x40. Consider removing the "placeholder='blur'" property to improve performance.`
)
}
if (!blurDataURL) {
const VALID_BLUR_EXT = ['jpeg', 'png', 'webp', 'avif'] // should match next-image-loader
throw new Error(
`Image with src "${src}" has "placeholder='blur'" property but is missing the "blurDataURL" property.
Possible solutions: Possible solutions:
- Add a "blurDataURL" property, the contents should be a small Data URL to represent the image - Add a "blurDataURL" property, the contents should be a small Data URL to represent the image
- Change the "src" property to a static import with one of the supported file types: ${VALID_BLUR_EXT.join( - Change the "src" property to a static import with one of the supported file types: ${VALID_BLUR_EXT.join(
...@@ -574,80 +575,81 @@ export default function Image({ ...@@ -574,80 +575,81 @@ export default function Image({
)} )}
- Remove the "placeholder" property, effectively no blur effect - Remove the "placeholder" property, effectively no blur effect
Read more: https://nextjs.org/docs/messages/placeholder-blur-data-url` Read more: https://nextjs.org/docs/messages/placeholder-blur-data-url`
) )
}
} }
} if ('ref' in rest) {
if ('ref' in rest) {
warnOnce(
`Image with src "${src}" is using unsupported "ref" property. Consider using the "onLoadingComplete" property instead.`
)
}
if (!unoptimized && loader !== defaultImageLoader) {
const urlStr = loader({
config,
src,
width: widthInt || 400,
quality: qualityInt || 75,
})
let url: URL | undefined
try {
url = new URL(urlStr)
} catch (err) {}
if (urlStr === src || (url && url.pathname === src && !url.search)) {
warnOnce( warnOnce(
`Image with src "${src}" has a "loader" property that does not implement width. Please implement it or use the "unoptimized" property instead.` + `Image with src "${src}" is using unsupported "ref" property. Consider using the "onLoadingComplete" property instead.`
`\nRead more: https://nextjs.org/docs/messages/next-image-missing-loader-width`
) )
} }
}
if (style) { if (!unoptimized && loader !== defaultImageLoader) {
let overwrittenStyles = Object.keys(style).filter( const urlStr = loader({
(key) => key in layoutStyle config,
) src,
if (overwrittenStyles.length) { width: widthInt || 400,
warnOnce( quality: qualityInt || 75,
`Image with src ${src} is assigned the following styles, which are overwritten by automatically-generated styles: ${overwrittenStyles.join( })
', ' let url: URL | undefined
)}` try {
url = new URL(urlStr)
} catch (err) {}
if (urlStr === src || (url && url.pathname === src && !url.search)) {
warnOnce(
`Image with src "${src}" has a "loader" property that does not implement width. Please implement it or use the "unoptimized" property instead.` +
`\nRead more: https://nextjs.org/docs/messages/next-image-missing-loader-width`
)
}
}
if (style) {
let overwrittenStyles = Object.keys(style).filter(
(key) => key in layoutStyle
) )
if (overwrittenStyles.length) {
warnOnce(
`Image with src ${src} is assigned the following styles, which are overwritten by automatically-generated styles: ${overwrittenStyles.join(
', '
)}`
)
}
} }
}
if ( if (
typeof window !== 'undefined' && typeof window !== 'undefined' &&
!perfObserver && !perfObserver &&
window.PerformanceObserver window.PerformanceObserver
) { ) {
perfObserver = new PerformanceObserver((entryList) => { perfObserver = new PerformanceObserver((entryList) => {
for (const entry of entryList.getEntries()) { for (const entry of entryList.getEntries()) {
// @ts-ignore - missing "LargestContentfulPaint" class with "element" prop // @ts-ignore - missing "LargestContentfulPaint" class with "element" prop
const imgSrc = entry?.element?.src || '' const imgSrc = entry?.element?.src || ''
const lcpImage = allImgs.get(imgSrc) const lcpImage = allImgs.get(imgSrc)
if ( if (
lcpImage && lcpImage &&
!lcpImage.priority && !lcpImage.priority &&
lcpImage.placeholder !== 'blur' && lcpImage.placeholder !== 'blur' &&
!lcpImage.src.startsWith('data:') && !lcpImage.src.startsWith('data:') &&
!lcpImage.src.startsWith('blob:') !lcpImage.src.startsWith('blob:')
) { ) {
// https://web.dev/lcp/#measure-lcp-in-javascript // https://web.dev/lcp/#measure-lcp-in-javascript
warnOnce( warnOnce(
`Image with src "${lcpImage.src}" was detected as the Largest Contentful Paint (LCP). Please add the "priority" property if this image is above the fold.` + `Image with src "${lcpImage.src}" was detected as the Largest Contentful Paint (LCP). Please add the "priority" property if this image is above the fold.` +
`\nRead more: https://nextjs.org/docs/api-reference/next/image#priority` `\nRead more: https://nextjs.org/docs/api-reference/next/image#priority`
) )
}
} }
}
})
try {
perfObserver.observe({
type: 'largest-contentful-paint',
buffered: true,
}) })
} catch (err) { try {
// Log error but don't crash the app perfObserver.observe({
console.error(err) type: 'largest-contentful-paint',
buffered: true,
})
} catch (err) {
// Log error but don't crash the app
console.error(err)
}
} }
} }
} }
...@@ -881,6 +883,11 @@ const ImageElement = ({ ...@@ -881,6 +883,11 @@ const ImageElement = ({
style={{ ...imgStyle, ...blurStyle }} style={{ ...imgStyle, ...blurStyle }}
ref={useCallback( ref={useCallback(
(img: ImgElementWithDataProp) => { (img: ImgElementWithDataProp) => {
if (process.env.NODE_ENV !== 'production') {
if (img && !srcString) {
console.error(`Image is missing required "src" property:`, img)
}
}
setIntersection(img) setIntersection(img)
if (img?.complete) { if (img?.complete) {
handleLoading( handleLoading(
......
...@@ -386,10 +386,13 @@ function runTests(mode) { ...@@ -386,10 +386,13 @@ function runTests(mode) {
it('should show missing src error', async () => { it('should show missing src error', async () => {
const browser = await webdriver(appPort, '/docs/missing-src') const browser = await webdriver(appPort, '/docs/missing-src')
expect(await hasRedbox(browser)).toBe(true) expect(await hasRedbox(browser)).toBe(false)
expect(await getRedboxHeader(browser)).toContain(
'Image is missing required "src" property. Make sure you pass "src" in props to the `next/image` component. Received: {"width":200}' await check(async () => {
) return (await browser.log('browser'))
.map((log) => log.message)
.join('\n')
}, /Image is missing required "src" property/gm)
}) })
it('should show invalid src error', async () => { it('should show invalid src error', async () => {
......
...@@ -746,10 +746,13 @@ function runTests(mode) { ...@@ -746,10 +746,13 @@ function runTests(mode) {
it('should show missing src error', async () => { it('should show missing src error', async () => {
const browser = await webdriver(appPort, '/missing-src') const browser = await webdriver(appPort, '/missing-src')
expect(await hasRedbox(browser)).toBe(true) expect(await hasRedbox(browser)).toBe(false)
expect(await getRedboxHeader(browser)).toContain(
'Image is missing required "src" property. Make sure you pass "src" in props to the `next/image` component. Received: {"width":200}' await check(async () => {
) return (await browser.log('browser'))
.map((log) => log.message)
.join('\n')
}, /Image is missing required "src" property/gm)
}) })
it('should show invalid src error', async () => { it('should show invalid src error', async () => {
......
...@@ -130,10 +130,13 @@ function runTests(mode) { ...@@ -130,10 +130,13 @@ function runTests(mode) {
it('should show missing src error', async () => { it('should show missing src error', async () => {
const browser = await webdriver(appPort, '/docs/missing-src') const browser = await webdriver(appPort, '/docs/missing-src')
expect(await hasRedbox(browser)).toBe(true) expect(await hasRedbox(browser)).toBe(false)
expect(await getRedboxHeader(browser)).toContain(
'Image is missing required "src" property. Make sure you pass "src" in props to the `next/image` component. Received: {"width":200}' await check(async () => {
) return (await browser.log('browser'))
.map((log) => log.message)
.join('\n')
}, /Image is missing required "src" property/gm)
}) })
it('should show invalid src error', async () => { it('should show invalid src error', async () => {
......
...@@ -605,10 +605,13 @@ function runTests(mode) { ...@@ -605,10 +605,13 @@ function runTests(mode) {
it('should show missing src error', async () => { it('should show missing src error', async () => {
const browser = await webdriver(appPort, '/missing-src') const browser = await webdriver(appPort, '/missing-src')
expect(await hasRedbox(browser)).toBe(true) expect(await hasRedbox(browser)).toBe(false)
expect(await getRedboxHeader(browser)).toContain(
'Image is missing required "src" property. Make sure you pass "src" in props to the `next/image` component. Received: {"width":200}' await check(async () => {
) return (await browser.log('browser'))
.map((log) => log.message)
.join('\n')
}, /Image is missing required "src" property/gm)
}) })
it('should show invalid src error', async () => { it('should show invalid src error', async () => {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment