Skip to content

Commit

Permalink
Dedupe meta tags (#8960)
Browse files Browse the repository at this point in the history
* Dedupe meta tag in favor of custom tag defined in _app

* Add test

* Fix comments
  • Loading branch information
melanieseltzer authored and Timer committed Oct 18, 2019
1 parent 16e0ff9 commit c650ed9
Show file tree
Hide file tree
Showing 4 changed files with 40 additions and 1 deletion.
6 changes: 6 additions & 0 deletions packages/next/next-server/lib/head.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,12 @@ function unique() {
keys.add(h.key)
return true
}

// If custom meta tag has been added the key will be prepended with `.$`, we can
// check for this and dedupe in favor of the custom one, so the default
// is not rendered as well
if (keys.has(`.$${h.key}`)) return false

switch (h.type) {
case 'title':
case 'base':
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import React from 'react'
import Head from 'next/head'

export default () => (
<div>
<Head>
{/* this will not render */}
<meta charSet='utf-8' key='charSet' />
{/* this will override the default (same key as the default) */}
<meta charSet='iso-8859-5' key='charSet' />

{/* this will not render */}
<meta name='viewport' content='width=device-width' key='viewport' />
{/* this will override the default (same key as the default) */}
<meta
name='viewport'
content='width=device-width,initial-scale=1'
key='viewport'
/>
</Head>
<h1>Meta tags with same keys as default get deduped</h1>
</div>
)
2 changes: 1 addition & 1 deletion test/integration/client-navigation/pages/head.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ export default () => (
{/* this will get rendered */}
<meta charSet='iso-8859-5' />

{/* this not render */}
{/* this will not render */}
<meta name='viewport' content='width=device-width' />
{/* this will override the default */}
<meta name='viewport' content='width=device-width,initial-scale=1' />
Expand Down
10 changes: 10 additions & 0 deletions test/integration/client-navigation/test/rendering.js
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,16 @@ export default function (render, fetch) {
)
})

test('header helper dedupes tags with the same key as the default', async () => {
const html = await render('/head')
expect(html).toContain('<meta charSet="iso-8859-5"/>')
expect(html).not.toContain('<meta charSet="utf-8"/>')
expect(html).toContain(
'<meta name="viewport" content="width=device-width,initial-scale=1"/>'
)
expect(html).not.toContain('<meta name="width=device-width"/>')
})

test('header helper avoids dedupe of specific tags', async () => {
const html = await render('/head')
expect(html).toContain('<meta property="article:tag" content="tag1"/>')
Expand Down

0 comments on commit c650ed9

Please sign in to comment.