Unverified Commit 7f73b658 authored by Yamagishi Kazutoshi's avatar Yamagishi Kazutoshi Committed by GitHub

Escape href when detecting already existing preload tags (#20782)

When Image Optimization is enabled, if the URL of the image is not correct as a regular expression (e.g. `/image.png?lang=c++`), Next.js will give an error and fail to build.
parent 22e3f8c2
import escapeRegexp from 'next/dist/compiled/escape-string-regexp'
import { parse, HTMLElement } from 'node-html-parser' import { parse, HTMLElement } from 'node-html-parser'
import { OPTIMIZED_FONT_PROVIDERS } from './constants' import { OPTIMIZED_FONT_PROVIDERS } from './constants'
...@@ -188,7 +189,8 @@ function isImgEligible(imgElement: HTMLElement): boolean { ...@@ -188,7 +189,8 @@ function isImgEligible(imgElement: HTMLElement): boolean {
} }
function preloadTagAlreadyExists(html: string, href: string) { function preloadTagAlreadyExists(html: string, href: string) {
const regex = new RegExp(`<link[^>]*href[^>]*${href}`) const escapedHref = escapeRegexp(href)
const regex = new RegExp(`<link[^>]*href[^>]*${escapedHref}`)
return html.match(regex) return html.match(regex)
} }
......
import React from 'react'
const Page = () => {
return (
<div>
<img src="https://image.example.org/?lang[]=c++" />
<img src="/api/image?lang[]=c++" />
</div>
)
}
export default Page
...@@ -25,6 +25,18 @@ function runTests() { ...@@ -25,6 +25,18 @@ function runTests() {
describe('On an SSR page', () => { describe('On an SSR page', () => {
checkImagesOnPage('/stars') checkImagesOnPage('/stars')
}) })
describe('On a static page with querystring ', () => {
it('should preload exactly eligible image', async () => {
const html = await renderViaHTTP(appPort, '/with-querystring')
expect(html).toContain(
'<link rel="preload" href="https://image.example.org/?lang[]=c++" as="image"/>'
)
expect(html).toContain(
'<link rel="preload" href="/api/image?lang[]=c++" as="image"/>'
)
})
})
} }
function checkImagesOnPage(path) { function checkImagesOnPage(path) {
......
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