Skip to content

Commit

Permalink
Provide default metadataBase for local and vercel deployment
Browse files Browse the repository at this point in the history
always resolve full url for opengraph images

update ut types

hoist

logs metadataBase in dev

revert test

fix lint and test

fix test

fix test
  • Loading branch information
huozhi committed Mar 28, 2023
1 parent 18131c7 commit 273bd28
Show file tree
Hide file tree
Showing 7 changed files with 49 additions and 20 deletions.
9 changes: 7 additions & 2 deletions packages/next/src/lib/metadata/default-metadata.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,17 @@
import React from 'react'
import type { ResolvedMetadata } from './types/metadata-interface'

export const createDefaultMetadata = (): ResolvedMetadata => {
export function createDefaultMetadata(): ResolvedMetadata {
let defaultMetadataBase = new URL('http://n')
if (process.env.NODE_ENV === 'production' && process.env.VERCEL_URL) {
defaultMetadataBase = new URL(`https://${process.env.VERCEL_URL}`)
}

return {
viewport: 'width=device-width, initial-scale=1',
metadataBase: defaultMetadataBase,

// Other values are all null
metadataBase: null,
title: null,
description: null,
applicationName: null,
Expand Down
4 changes: 2 additions & 2 deletions packages/next/src/lib/metadata/resolvers/resolve-opengraph.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,11 +43,11 @@ function resolveImages(
resolvedImages?.forEach((item, index, array) => {
if (isStringOrURL(item)) {
array[index] = {
url: metadataBase ? resolveUrl(item, metadataBase)! : item,
url: resolveUrl(item, metadataBase)!,
}
} else {
// Update image descriptor url
item.url = metadataBase ? resolveUrl(item.url, metadataBase)! : item.url
item.url = resolveUrl(item.url, metadataBase)!
}
})
return resolvedImages
Expand Down
13 changes: 11 additions & 2 deletions packages/next/src/lib/metadata/resolvers/resolve-url.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import path from '../../../shared/lib/isomorphic/path'
import { warnOnce } from '../../../shared/lib/utils/warn-once'

function isStringOrURL(icon: any): icon is string | URL {
return typeof icon === 'string' || icon instanceof URL
Expand All @@ -17,10 +18,18 @@ function resolveUrl(
return parsedUrl
} catch (_) {}

if (!metadataBase)
if (!metadataBase) {
throw new Error(
`metadata.metadataBase needs to be provided for resolving absolute URLs: ${url}`
`metadata.metadataBase needs to be provided for resolving absolute URL: ${url}`
)
}
if (metadataBase.origin === 'http://n') {
metadataBase = new URL('http://localhost:3000')
// Development mode warning
warnOnce(
`"metadataBase" is not set and fallbacks to "http://localhost:3000", Please specify it in root layout to resolve urls as absolute`
)
}

// Handle relative or absolute paths
const basePath = metadataBase.pathname || '/'
Expand Down
1 change: 1 addition & 0 deletions packages/next/src/server/app-render/app-render.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1037,6 +1037,7 @@ export async function renderToHTMLOrFlight(
<MetadataTree key={requestId} metadata={metadataItems} />
</>
),
// {/* `http://localhost:3000${req.url}` */}
injectedCSS: new Set(),
injectedFontPreloadTags: new Set(),
rootLayoutIncluded: false,
Expand Down
1 change: 0 additions & 1 deletion test/e2e/app-dir/metadata-dynamic-routes/app/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,5 @@ export default function Page() {
}

export const metadata = {
metadataBase: new URL('https://deploy-preview-abc.vercel.app'),
title: 'index page',
}
33 changes: 24 additions & 9 deletions test/e2e/app-dir/metadata-dynamic-routes/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,11 @@ createNextDescribe(
'app dir - metadata dynamic routes',
{
files: __dirname,
skipDeployment: true,
dependencies: {
'@vercel/og': '0.4.1',
},
},
({ next, isNextDev }) => {
({ next, isNextDev, isNextDeploy }) => {
describe('text routes', () => {
it('should handle robots.[ext] dynamic routes', async () => {
const res = await next.fetch('/robots.txt')
Expand Down Expand Up @@ -148,6 +147,10 @@ createNextDescribe(
})

it('should inject dynamic metadata properly to head', async () => {
const logs = []
next.on('stderr', (log) => {
logs.push(log)
})
const $ = await next.render$('/')
const $icon = $('link[rel="icon"]')
const $appleIcon = $('link[rel="apple-touch-icon"]')
Expand All @@ -158,6 +161,14 @@ createNextDescribe(
'content'
)

if (isNextDev) {
expect(
logs.includes(
`"metadataBase" is not set and fallbacks to "http://localhost:3000", Please specify it in root layout to resolve urls as absolute\n`
)
).toBe(true)
}

// non absolute urls
expect($icon.attr('href')).toContain('/icon')
expect($icon.attr('href')).toMatch(hashRegex)
Expand All @@ -172,14 +183,18 @@ createNextDescribe(
expect(twitterTitle).toBe('Twitter - Next.js App')
expect(twitterDescription).toBe('Twitter - This is a Next.js App')

// absolute urls
expect(ogImageUrl).toContain(
`https://deploy-preview-abc.vercel.app/opengraph-image`
)
if (isNextDeploy) {
// absolute urls
expect(ogImageUrl).toMatch(/https:\/\/\w+.vercel.app\/opengraph-image/)
expect(twitterImageUrl).toMatch(
/https:\/\/\w+.vercel.app\/twitter-image/
)
} else {
// absolute urls
expect(ogImageUrl).toMatch(/http:\/\/localhost:\d+\/opengraph-image/)
expect(twitterImageUrl).toMatch(/http:\/\/localhost:\d+\/twitter-image/)
}
expect(ogImageUrl).toMatch(hashRegex)
expect(twitterImageUrl).toContain(
`https://deploy-preview-abc.vercel.app/twitter-image`
)
expect(twitterImageUrl).toMatch(hashRegex)

// alt text
Expand Down
8 changes: 4 additions & 4 deletions test/e2e/app-dir/metadata/metadata.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -257,7 +257,7 @@ createNextDescribe(

it('should support alternate tags', async () => {
const browser = await next.browser('/alternate')
await checkLink(browser, 'canonical', 'https://example.com')
await checkLink(browser, 'canonical', 'https://example.com/')
await checkMeta(
browser,
'en-US',
Expand All @@ -277,7 +277,7 @@ createNextDescribe(
await checkMeta(
browser,
'only screen and (max-width: 600px)',
'/mobile',
'http://localhost:3000/mobile',
'media',
'link',
'href'
Expand All @@ -286,11 +286,11 @@ createNextDescribe(

await matchDom('link', 'title="js title"', {
type: 'application/rss+xml',
href: 'blog/js.rss',
href: 'http://localhost:3000/blog/js.rss',
})
await matchDom('link', 'title="rss"', {
type: 'application/rss+xml',
href: 'blog.rss',
href: 'http://localhost:3000/blog.rss',
})
})

Expand Down

0 comments on commit 273bd28

Please sign in to comment.