Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Add support for wildcard patterns in image.domains #18730

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 17 additions & 1 deletion packages/next/client/image.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -583,7 +583,23 @@ function defaultLoader({ root, src, width, quality }: LoaderProps): string {
)
}

if (!configDomains.includes(parsedSrc.hostname)) {
if (
!configDomains.some((domain) => {
if (domain.includes('*')) {
const domainExpr = new RegExp(
'^' +
domain
.split(/\*+/)
.map((s) => s.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&'))
.join('.*') +
'$'
)
return domainExpr.test(parsedSrc.hostname)
} else {
return parsedSrc.hostname === domain
}
})
) {
throw new Error(
`Invalid src prop (${src}) on \`next/image\`, hostname "${parsedSrc.hostname}" is not configured under images in your \`next.config.js\`\n` +
`See more info: https://err.sh/nextjs/next-image-unconfigured-host`
Expand Down
18 changes: 17 additions & 1 deletion packages/next/next-server/server/image-optimizer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,23 @@ export async function imageOptimizer(
return { finished: true }
}

if (!domains.includes(hrefParsed.hostname)) {
if (
!domains.some((domain) => {
if (domain.includes('*')) {
const domainExpr = new RegExp(
'^' +
domain
.split(/\*+/)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we want to allow multiple asterisks?

.map((s) => s.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&'))
Copy link
Member

@styfle styfle Jul 22, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this regex to escape regex? MDN has a slightly different example https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#escaping

I wonder if we can do this asterisk matching without regex and avoid escaping.

.join('.*') +
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
.join('.*') +
.join('.+') +

I think this should match one or more, right?

'$'
)
return domainExpr.test(hrefParsed.hostname)
} else {
return hrefParsed.hostname === domain
}
})
) {
res.statusCode = 400
res.end('"url" parameter is not allowed')
return { finished: true }
Expand Down
5 changes: 5 additions & 0 deletions test/integration/image-domain-pattern/next.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
module.exports = {
images: {
domains: ['*.placeholder.com'],
},
}
13 changes: 13 additions & 0 deletions test/integration/image-domain-pattern/pages/invalid.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import React from 'react'
import Image from 'next/image'

const Invalid = () => {
return (
<div>
<Image src="https://via.invalid.com/500" width={500} height={500} />
<p id="stubtext">This is a page with errors</p>
</div>
)
}

export default Invalid
13 changes: 13 additions & 0 deletions test/integration/image-domain-pattern/pages/valid.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import React from 'react'
import Image from 'next/image'

const Page = () => {
return (
<div>
<Image src="https://via.placeholder.com/500" width={500} height={500} />
<p>This is a valid domain</p>
</div>
)
}

export default Page
32 changes: 32 additions & 0 deletions test/integration/image-domain-pattern/test/index.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/* eslint-env jest */

import { join } from 'path'
import { renderViaHTTP, findPort, launchApp, killApp } from 'next-test-utils'

jest.setTimeout(1000 * 60 * 2)

const appDir = join(__dirname, '..')
let appPort
let app

describe('Image Component Domain Pattern', () => {
describe('next dev', () => {
beforeAll(async () => {
appPort = await findPort()
app = await launchApp(appDir, appPort)
})
afterAll(() => killApp(app))

it('should render the valid Image usage and not print error', async () => {
const html = await renderViaHTTP(appPort, '/valid', {})
expect(html).toMatch(/This is a valid domain/)
expect(html).not.toMatch(/hostname .* is not configured under images/)
})

it('should print error when invalid Image usage', async () => {
const html = await renderViaHTTP(appPort, '/invalid', {})
expect(html).toMatch(/hostname .* is not configured under images/)
expect(html).not.toMatch(/This is a page with errors/)
})
})
})
33 changes: 33 additions & 0 deletions test/integration/image-optimizer/test/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -564,4 +564,37 @@ describe('Image Optimizer', () => {
expect(res.status).toBe(404)
})
})

describe('dev support next.config.js domains pattern', () => {
beforeAll(async () => {
const json = JSON.stringify({
images: {
domains: ['*.placeholder.com'],
},
})
nextConfig.replace('{ /* replaceme */ }', json)
appPort = await findPort()
app = await launchApp(appDir, appPort)
})
afterAll(async () => {
await killApp(app)
nextConfig.restore()
await fs.remove(imagesDir)
})
it('should 200 when correct domain is used', async () => {
const size = 384 // defaults defined in server/config.ts
const query = { w: size, q: 90, url: 'https://via.placeholder.com/500' }
const opts = { headers: { accept: 'image/webp' } }
const res = await fetchViaHTTP(appPort, '/_next/image', query, opts)
expect(res.status).toBe(200)
})

it('should 400 when invalid domain is used', async () => {
const size = 384 // defaults defined in server/config.ts
const query = { w: size, q: 90, url: 'https://via.invalid.com/500' }
const opts = { headers: { accept: 'image/webp' } }
const res = await fetchViaHTTP(appPort, '/_next/image', query, opts)
expect(res.status).toBe(400)
})
})
})