Skip to content

Commit

Permalink
fix(image-optimizer): allow external image urls with _next/image path…
Browse files Browse the repository at this point in the history
…name to be rendered via Image component
  • Loading branch information
abhi12299 committed Sep 2, 2024
1 parent d3f5532 commit f038593
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 5 deletions.
15 changes: 10 additions & 5 deletions packages/next/src/server/image-optimizer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -215,21 +215,26 @@ export class ImageOptimizerCache {
}
}

let isAbsolute = !url.startsWith('/')

const parsedUrl = parseUrl(url)
if (parsedUrl) {
// if the url is external (matching with remote patterns), we can allow it
const isExternalUrlWithMatch =
isAbsolute && hasMatch(domains, remotePatterns, parsedUrl)
const decodedPathname = decodeURIComponent(parsedUrl.pathname)
if (/\/_next\/image($|\/)/.test(decodedPathname)) {
if (
/\/_next\/image($|\/)/.test(decodedPathname) &&
!isExternalUrlWithMatch
) {
return {
errorMessage: '"url" parameter cannot be recursive',
}
}
}

let isAbsolute: boolean

if (url.startsWith('/')) {
if (!isAbsolute) {
href = url
isAbsolute = false
} else {
let hrefParsed: URL

Expand Down
11 changes: 11 additions & 0 deletions test/integration/image-optimizer/test/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1064,6 +1064,17 @@ export function runTests(ctx: RunTestsCtx) {
})
})

it('should pass with external absolute next image url', async () => {
const query = {
url: `https://example.com/_next/image?url=test.png&w=1&q=1`,
w: ctx.w,
q: 1,
}
const res = await fetchViaHTTP(ctx.appPort, '/_next/image', query, {})
// the example image doesn't exist, so we do not check for 200 status code
expect(res.status).not.toBe(400)
})

it('should fail when internal url is not an image', async () => {
const url = `/api/no-header`
const query = { url, w: ctx.w, q: 39 }
Expand Down

0 comments on commit f038593

Please sign in to comment.