Skip to content

Commit

Permalink
Add domains check
Browse files Browse the repository at this point in the history
  • Loading branch information
ijjk committed Oct 23, 2020
1 parent 129d6f5 commit fdebf77
Show file tree
Hide file tree
Showing 4 changed files with 44 additions and 2 deletions.
6 changes: 6 additions & 0 deletions packages/next/build/webpack-config.ts
Expand Up @@ -994,6 +994,12 @@ export default async function getBaseWebpackConfig(
sizes: config.images.sizes,
path: config.images.path,
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_HAS_REWRITES': JSON.stringify(hasRewrites),
Expand Down
10 changes: 10 additions & 0 deletions packages/next/client/image.tsx
Expand Up @@ -358,6 +358,16 @@ function defaultLoader({ root, src, width, quality }: LoaderProps): string {
)}`
)
}

if (src && !src.startsWith('/') && imageData.domains) {
const parsedSrc = new URL(src)

if (!imageData.domains.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=${
Expand Down
Expand Up @@ -5,7 +5,11 @@ const Page = () => {
return (
<div>
<p>Hello World</p>
<Image id="unsized-image" src="/test.png" unsized></Image>
<Image
id="unsized-image"
src="https://google.com/test.png"
unsized
></Image>
<p id="stubtext">This is the index page</p>
</div>
)
Expand Down
24 changes: 23 additions & 1 deletion test/integration/image-component/default/test/index.test.js
Expand Up @@ -8,6 +8,8 @@ import {
nextStart,
nextBuild,
check,
hasRedbox,
getRedboxHeader,
} from 'next-test-utils'
import webdriver from 'next-webdriver'
import fs from 'fs-extra'
Expand All @@ -20,7 +22,7 @@ const nextConfig = join(appDir, 'next.config.js')
let appPort
let app

function runTests() {
function runTests(mode) {
it('should load the images', async () => {
let browser
try {
Expand Down Expand Up @@ -73,6 +75,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 optimizer 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', () => {
Expand Down

0 comments on commit fdebf77

Please sign in to comment.