Unverified Commit 9c65c994 authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

Add next/image default loader errors (#18152)

* Add next/image default loader errors

* Add domains check

* Apply suggestions from PR

* Update test
parent 33eac8ac
...@@ -994,6 +994,12 @@ export default async function getBaseWebpackConfig( ...@@ -994,6 +994,12 @@ export default async function getBaseWebpackConfig(
sizes: config.images.sizes, sizes: config.images.sizes,
path: config.images.path, path: config.images.path,
loader: config.images.loader, loader: config.images.loader,
...(dev
? {
// pass domains in development to allow validating on the client
domains: config.images.domains,
}
: {}),
}), }),
'process.env.__NEXT_ROUTER_BASEPATH': JSON.stringify(config.basePath), 'process.env.__NEXT_ROUTER_BASEPATH': JSON.stringify(config.basePath),
'process.env.__NEXT_HAS_REWRITES': JSON.stringify(hasRewrites), 'process.env.__NEXT_HAS_REWRITES': JSON.stringify(hasRewrites),
......
...@@ -17,6 +17,7 @@ type ImageData = { ...@@ -17,6 +17,7 @@ type ImageData = {
sizes: number[] sizes: number[]
loader: LoaderKey loader: LoaderKey
path: string path: string
domains?: string[]
} }
type ImageProps = Omit< type ImageProps = Omit<
...@@ -34,7 +35,12 @@ type ImageProps = Omit< ...@@ -34,7 +35,12 @@ type ImageProps = Omit<
) )
const imageData: ImageData = process.env.__NEXT_IMAGE_OPTS as any const imageData: ImageData = process.env.__NEXT_IMAGE_OPTS as any
const { sizes: configSizes, loader: configLoader, path: configPath } = imageData const {
sizes: configSizes,
loader: configLoader,
path: configPath,
domains: configDomains,
} = imageData
configSizes.sort((a, b) => a - b) // smallest to largest configSizes.sort((a, b) => a - b) // smallest to largest
const largestSize = configSizes[configSizes.length - 1] const largestSize = configSizes[configSizes.length - 1]
...@@ -349,6 +355,42 @@ function cloudinaryLoader({ root, src, width, quality }: LoaderProps): string { ...@@ -349,6 +355,42 @@ function cloudinaryLoader({ root, src, width, quality }: LoaderProps): string {
} }
function defaultLoader({ root, src, width, quality }: LoaderProps): string { function defaultLoader({ root, src, width, quality }: LoaderProps): string {
if (process.env.NODE_ENV !== 'production') {
const missingValues = []
// these should always be provided but make sure they are
if (!src) missingValues.push('src')
if (!width) missingValues.push('width')
if (missingValues.length > 0) {
throw new Error(
`Next Image Optimization requires ${missingValues.join(
', '
)} to be provided. Make sure you pass them as props to the \`next/image\` component. Received: ${JSON.stringify(
{ src, width, quality }
)}`
)
}
if (src && !src.startsWith('/') && configDomains) {
let parsedSrc: URL
try {
parsedSrc = new URL(src)
} catch (err) {
console.error(err)
throw new Error(
`Failed to parse "${src}" if using relative image it must start with a leading slash "/" or be an absolute URL`
)
}
if (!configDomains.includes(parsedSrc.hostname)) {
throw new Error(
`Invalid src prop (${src}) on \`next/image\`, hostname is not configured under images in your \`next.config.js\``
)
}
}
}
return `${root}?url=${encodeURIComponent(src)}&w=${width}&q=${ return `${root}?url=${encodeURIComponent(src)}&w=${width}&q=${
quality || '100' quality || '100'
}` }`
......
import React from 'react'
import Image from 'next/image'
const Page = () => {
return (
<div>
<p>Hello World</p>
<Image src="https://google.com/test.png" unsized></Image>
</div>
)
}
export default Page
import React from 'react'
import Image from 'next/image'
const Page = () => {
return (
<div>
<Image width={200}></Image>
</div>
)
}
export default Page
...@@ -8,6 +8,8 @@ import { ...@@ -8,6 +8,8 @@ import {
nextStart, nextStart,
nextBuild, nextBuild,
check, check,
hasRedbox,
getRedboxHeader,
} from 'next-test-utils' } from 'next-test-utils'
import webdriver from 'next-webdriver' import webdriver from 'next-webdriver'
import fs from 'fs-extra' import fs from 'fs-extra'
...@@ -20,7 +22,7 @@ const nextConfig = join(appDir, 'next.config.js') ...@@ -20,7 +22,7 @@ const nextConfig = join(appDir, 'next.config.js')
let appPort let appPort
let app let app
function runTests() { function runTests(mode) {
it('should load the images', async () => { it('should load the images', async () => {
let browser let browser
try { try {
...@@ -79,6 +81,26 @@ function runTests() { ...@@ -79,6 +81,26 @@ function runTests() {
} }
} }
}) })
if (mode === 'dev') {
it('should show missing src error', async () => {
const browser = await webdriver(appPort, '/missing-src')
await hasRedbox(browser)
expect(await getRedboxHeader(browser)).toContain(
'Next Image Optimization requires src to be provided. Make sure you pass them as props to the `next/image` component. Received: {"width":1200}'
)
})
it('should show invalid src error', async () => {
const browser = await webdriver(appPort, '/invalid-src')
await hasRedbox(browser)
expect(await getRedboxHeader(browser)).toContain(
'Invalid src prop (https://google.com/test.png) on `next/image`, hostname is not configured under images in your `next.config.js`'
)
})
}
} }
describe('Image Component Tests', () => { describe('Image Component Tests', () => {
......
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