next.js: URL in Metadata will encodeURLComponent unexpectedly. Url query `&` will encode into `&` automatically
Verify canary release
- I verified that the issue exists in the latest Next.js canary release
Provide environment information
Operating System:
Platform: darwin
Arch: arm64
Version: Darwin Kernel Version 22.5.0: Thu Jun 8 22:21:34 PDT 2023; root:xnu-8796.121.3~7/RELEASE_ARM64_T8112
Binaries:
Node: 18.16.1
npm: 8.19.4
Yarn: 1.22.19
pnpm: 8.6.2
Relevant Packages:
next: 13.4.9
eslint-config-next: N/A
react: 18.2.0
react-dom: 18.2.0
typescript: 5.1.6
Next.js Config:
output: standalone
Which area(s) of Next.js are affected? (leave empty if unsure)
App Router, Metadata (metadata, generateMetadata, next/head)
Link to the code that reproduces this issue or a replay of the bug
https://github.com/Innei/nextjs-metadata-url-encode-reproduction
To Reproduce
next dev- Open the home page’s source view.
Describe the Bug
Next.js metadata url will encodeURLComponent unexpectedly.
export const generateMetadata = async (): Promise<Metadata> => {
const ogUrl = new URL('http://localhost:3000/og.png')
ogUrl.searchParams.set('title', 'Nextjs')
ogUrl.searchParams.set('description', 'description - Nextjs')
return {
title: 'Nextjs',
openGraph: {
images: ogUrl,
},
}
}
and generate the code of <meta> tag.
<meta property="og:image" content="http://localhost:3000/og.png?title=Nextjs&description=description+-+Nextjs"/>
The & will encode to & unexpected.
Expected Behavior
No need to automatically encode HTML characters.
Which browser are you using? (if relevant)
No response
How are you deploying your application? (if relevant)
No response
About this issue
- Original URL
- State: closed
- Created 3 years ago
- Reactions: 9
- Comments: 18 (3 by maintainers)
Hi @gnoff. I created a minimal reproduction of this issue here: https://github.com/mpereira/react-ssr-meta-tags-escape-bug
I’ll echo below the details written in the README.
Since Next.js 13 it is possible to add Open Graph metadata via the
generateMetadatafunction in apage.tsxfile. In this project,app/page.tsxlooks like the following:Starting a development server with
npm run devand accessingview-source:http://localhost:3000will show the following Open Graph tags:The query string separator (
?) is correctly not escaped in the resulting string, while the query string parameter separator (&) is incorrectly escaped to&.This results in a URL that won’t behave as expected. One example is a dynamic Open Graph image that depends on URL query parameters for its appearance.
Deployed to Vercel:
view-source:https://react-ssr-meta-tags-escape-bug.vercel.app