Skip to content

Commit

Permalink
Use vercel deployment url for metadataBase fallbacks
Browse files Browse the repository at this point in the history
  • Loading branch information
huozhi committed Apr 26, 2024
1 parent 3ae3802 commit 6ecbd23
Showing 1 changed file with 17 additions and 5 deletions.
22 changes: 17 additions & 5 deletions packages/next/src/lib/metadata/resolvers/resolve-url.ts
Expand Up @@ -9,6 +9,18 @@ function createLocalMetadataBase() {
return new URL(`http://localhost:${process.env.PORT || 3000}`)
}

function getPreviewDeploymentUrl(): URL | undefined {
const origin = process.env.VERCEL_BRANCH_URL || process.env.VERCEL_URL
if (!origin) return undefined
return new URL(`https://${origin}`)
}

function getProductionDeploymentUrl(): URL | undefined {
const origin = process.env.VERCEL_PROJECT_PRODUCTION_URL
if (!origin) return undefined
return new URL(`https://${origin}`)
}

// For deployment url for metadata routes, prefer to use the deployment url if possible
// as these routes are unique to the deployments url.
export function getSocialImageFallbackMetadataBase(metadataBase: URL | null): {
Expand All @@ -17,19 +29,19 @@ export function getSocialImageFallbackMetadataBase(metadataBase: URL | null): {
} {
const isMetadataBaseMissing = !metadataBase
const defaultMetadataBase = createLocalMetadataBase()
const deploymentUrl =
process.env.VERCEL_URL && new URL(`https://${process.env.VERCEL_URL}`)
const previewDeploymentUrl = getPreviewDeploymentUrl()
const productionDeploymentUrl = getProductionDeploymentUrl()

let fallbackMetadataBase
if (process.env.NODE_ENV === 'development') {
fallbackMetadataBase = defaultMetadataBase
} else {
fallbackMetadataBase =
process.env.NODE_ENV === 'production' &&
deploymentUrl &&
previewDeploymentUrl &&
process.env.VERCEL_ENV === 'preview'
? deploymentUrl
: metadataBase || deploymentUrl || defaultMetadataBase
? previewDeploymentUrl
: metadataBase || productionDeploymentUrl || defaultMetadataBase
}

return {
Expand Down

0 comments on commit 6ecbd23

Please sign in to comment.