Unverified Commit 7fa4946b authored by Jiachi Liu's avatar Jiachi Liu Committed by GitHub

Apply basePath for metadata image (#49226)

Fixes #49162

When user configures the `basePath` in `next.config.js`, we need to
apply it to metadata image path resolving
fix NEXT-1087
parent 7f6e8dbe
...@@ -553,6 +553,7 @@ export async function createEntrypoints( ...@@ -553,6 +553,7 @@ export async function createEntrypoints(
appDir, appDir,
appPaths: matchedAppPaths, appPaths: matchedAppPaths,
pageExtensions, pageExtensions,
basePath: config.basePath,
assetPrefix: config.assetPrefix, assetPrefix: config.assetPrefix,
nextConfigOutput: config.output, nextConfigOutput: config.output,
preferredRegion: staticInfo.preferredRegion, preferredRegion: staticInfo.preferredRegion,
...@@ -580,6 +581,7 @@ export async function createEntrypoints( ...@@ -580,6 +581,7 @@ export async function createEntrypoints(
appDir: appDir!, appDir: appDir!,
appPaths: matchedAppPaths, appPaths: matchedAppPaths,
pageExtensions, pageExtensions,
basePath: config.basePath,
assetPrefix: config.assetPrefix, assetPrefix: config.assetPrefix,
nextConfigOutput: config.output, nextConfigOutput: config.output,
// This isn't used with edge as it needs to be set on the entry module, which will be the `edgeServerEntry` instead. // This isn't used with edge as it needs to be set on the entry module, which will be the `edgeServerEntry` instead.
......
...@@ -64,12 +64,14 @@ export async function createStaticMetadataFromRoute( ...@@ -64,12 +64,14 @@ export async function createStaticMetadataFromRoute(
isRootLayoutOrRootPage, isRootLayoutOrRootPage,
loaderContext, loaderContext,
pageExtensions, pageExtensions,
basePath,
}: { }: {
segment: string segment: string
resolvePath: (pathname: string) => Promise<string> resolvePath: (pathname: string) => Promise<string>
isRootLayoutOrRootPage: boolean isRootLayoutOrRootPage: boolean
loaderContext: webpack.LoaderContext<any> loaderContext: webpack.LoaderContext<any>
pageExtensions: string[] pageExtensions: string[]
basePath: string
} }
) { ) {
let hasStaticMetadataFiles = false let hasStaticMetadataFiles = false
...@@ -124,6 +126,7 @@ export async function createStaticMetadataFromRoute( ...@@ -124,6 +126,7 @@ export async function createStaticMetadataFromRoute(
{ {
type, type,
segment, segment,
basePath,
pageExtensions, pageExtensions,
} }
)}!${filepath}${METADATA_RESOURCE_QUERY}` )}!${filepath}${METADATA_RESOURCE_QUERY}`
......
...@@ -33,6 +33,7 @@ export type AppLoaderOptions = { ...@@ -33,6 +33,7 @@ export type AppLoaderOptions = {
rootDir?: string rootDir?: string
tsconfigPath?: string tsconfigPath?: string
isDev?: boolean isDev?: boolean
basePath: string
nextConfigOutput?: NextConfig['output'] nextConfigOutput?: NextConfig['output']
} }
type AppLoader = webpack.LoaderDefinitionFunction<AppLoaderOptions> type AppLoader = webpack.LoaderDefinitionFunction<AppLoaderOptions>
...@@ -176,6 +177,7 @@ async function createTreeCodeFromPath( ...@@ -176,6 +177,7 @@ async function createTreeCodeFromPath(
resolveParallelSegments, resolveParallelSegments,
loaderContext, loaderContext,
pageExtensions, pageExtensions,
basePath,
}: { }: {
resolver: PathResolver resolver: PathResolver
resolvePath: (pathname: string) => Promise<string> resolvePath: (pathname: string) => Promise<string>
...@@ -184,6 +186,7 @@ async function createTreeCodeFromPath( ...@@ -184,6 +186,7 @@ async function createTreeCodeFromPath(
) => [key: string, segment: string | string[]][] ) => [key: string, segment: string | string[]][]
loaderContext: webpack.LoaderContext<AppLoaderOptions> loaderContext: webpack.LoaderContext<AppLoaderOptions>
pageExtensions: string[] pageExtensions: string[]
basePath: string
} }
) { ) {
const splittedPath = pagePath.split(/[\\/]/) const splittedPath = pagePath.split(/[\\/]/)
...@@ -258,6 +261,7 @@ async function createTreeCodeFromPath( ...@@ -258,6 +261,7 @@ async function createTreeCodeFromPath(
if (resolvedRouteDir) { if (resolvedRouteDir) {
metadata = await createStaticMetadataFromRoute(resolvedRouteDir, { metadata = await createStaticMetadataFromRoute(resolvedRouteDir, {
basePath,
segment: segmentPath, segment: segmentPath,
resolvePath, resolvePath,
isRootLayoutOrRootPage, isRootLayoutOrRootPage,
...@@ -427,6 +431,7 @@ const nextAppLoader: AppLoader = async function nextAppLoader() { ...@@ -427,6 +431,7 @@ const nextAppLoader: AppLoader = async function nextAppLoader() {
isDev, isDev,
nextConfigOutput, nextConfigOutput,
preferredRegion, preferredRegion,
basePath,
} = loaderOptions } = loaderOptions
const buildInfo = getModuleBuildInfo((this as any)._module) const buildInfo = getModuleBuildInfo((this as any)._module)
...@@ -535,6 +540,7 @@ const nextAppLoader: AppLoader = async function nextAppLoader() { ...@@ -535,6 +540,7 @@ const nextAppLoader: AppLoader = async function nextAppLoader() {
resolveParallelSegments, resolveParallelSegments,
loaderContext: this, loaderContext: this,
pageExtensions, pageExtensions,
basePath,
}) })
if (!rootLayout) { if (!rootLayout) {
...@@ -599,7 +605,7 @@ const nextAppLoader: AppLoader = async function nextAppLoader() { ...@@ -599,7 +605,7 @@ const nextAppLoader: AppLoader = async function nextAppLoader() {
export { renderToReadableStream, decodeReply, decodeAction } from 'react-server-dom-webpack/server.edge' export { renderToReadableStream, decodeReply, decodeAction } from 'react-server-dom-webpack/server.edge'
export const __next_app_webpack_require__ = __webpack_require__ export const __next_app_webpack_require__ = __webpack_require__
export { preloadStyle, preloadFont, preconnect } from 'next/dist/server/app-render/rsc/preloads' export { preloadStyle, preloadFont, preconnect } from 'next/dist/server/app-render/rsc/preloads'
export const originalPathname = "${page}" export const originalPathname = "${page}"
` `
......
...@@ -17,11 +17,12 @@ interface Options { ...@@ -17,11 +17,12 @@ interface Options {
segment: string segment: string
type: PossibleImageFileNameConvention type: PossibleImageFileNameConvention
pageExtensions: string[] pageExtensions: string[]
basePath: string
} }
async function nextMetadataImageLoader(this: any, content: Buffer) { async function nextMetadataImageLoader(this: any, content: Buffer) {
const options: Options = this.getOptions() const options: Options = this.getOptions()
const { type, segment, pageExtensions } = options const { type, segment, pageExtensions, basePath } = options
const numericSizes = type === 'twitter' || type === 'openGraph' const numericSizes = type === 'twitter' || type === 'openGraph'
const { resourcePath, rootContext: context } = this const { resourcePath, rootContext: context } = this
const { name: fileNameBase, ext } = path.parse(resourcePath) const { name: fileNameBase, ext } = path.parse(resourcePath)
...@@ -48,6 +49,7 @@ async function nextMetadataImageLoader(this: any, content: Buffer) { ...@@ -48,6 +49,7 @@ async function nextMetadataImageLoader(this: any, content: Buffer) {
const isDynamicResource = pageExtensions.includes(extension) const isDynamicResource = pageExtensions.includes(extension)
const pageSegment = isDynamicResource ? fileNameBase : interpolatedName const pageSegment = isDynamicResource ? fileNameBase : interpolatedName
const hashQuery = contentHash ? '?' + contentHash : '' const hashQuery = contentHash ? '?' + contentHash : ''
const pathnamePrefix = path.join(basePath, segment)
if (isDynamicResource) { if (isDynamicResource) {
// re-export and spread as `exportedImageData` to avoid non-exported error // re-export and spread as `exportedImageData` to avoid non-exported error
...@@ -59,7 +61,7 @@ async function nextMetadataImageLoader(this: any, content: Buffer) { ...@@ -59,7 +61,7 @@ async function nextMetadataImageLoader(this: any, content: Buffer) {
export default async function (props) { export default async function (props) {
const { __metadata_id__: _, ...params } = props.params const { __metadata_id__: _, ...params } = props.params
const imageUrl = fillMetadataSegment(${JSON.stringify( const imageUrl = fillMetadataSegment(${JSON.stringify(
segment pathnamePrefix
)}, params, ${JSON.stringify(pageSegment)}) )}, params, ${JSON.stringify(pageSegment)})
const { generateImageMetadata } = imageModule const { generateImageMetadata } = imageModule
...@@ -136,7 +138,7 @@ async function nextMetadataImageLoader(this: any, content: Buffer) { ...@@ -136,7 +138,7 @@ async function nextMetadataImageLoader(this: any, content: Buffer) {
export default (props) => { export default (props) => {
const imageData = ${JSON.stringify(imageData)} const imageData = ${JSON.stringify(imageData)}
const imageUrl = fillMetadataSegment(${JSON.stringify( const imageUrl = fillMetadataSegment(${JSON.stringify(
segment pathnamePrefix
)}, props.params, ${JSON.stringify(pageSegment)}) )}, props.params, ${JSON.stringify(pageSegment)})
return [{ return [{
......
...@@ -755,6 +755,7 @@ export default class HotReloader { ...@@ -755,6 +755,7 @@ export default class HotReloader {
rootDir: this.dir, rootDir: this.dir,
isDev: true, isDev: true,
tsconfigPath: this.config.typescript.tsconfigPath, tsconfigPath: this.config.typescript.tsconfigPath,
basePath: this.config.basePath,
assetPrefix: this.config.assetPrefix, assetPrefix: this.config.assetPrefix,
nextConfigOutput: this.config.output, nextConfigOutput: this.config.output,
preferredRegion: staticInfo.preferredRegion, preferredRegion: staticInfo.preferredRegion,
...@@ -840,6 +841,7 @@ export default class HotReloader { ...@@ -840,6 +841,7 @@ export default class HotReloader {
rootDir: this.dir, rootDir: this.dir,
isDev: true, isDev: true,
tsconfigPath: this.config.typescript.tsconfigPath, tsconfigPath: this.config.typescript.tsconfigPath,
basePath: this.config.basePath,
assetPrefix: this.config.assetPrefix, assetPrefix: this.config.assetPrefix,
nextConfigOutput: this.config.output, nextConfigOutput: this.config.output,
preferredRegion: staticInfo.preferredRegion, preferredRegion: staticInfo.preferredRegion,
......
...@@ -27,5 +27,12 @@ createNextDescribe( ...@@ -27,5 +27,12 @@ createNextDescribe(
.text() .text()
).toBe(`Page 2`) ).toBe(`Page 2`)
}) })
it('should prefix metadata og image with basePath', async () => {
const $ = await next.render$('/base/another')
const ogImageHref = $('meta[property="og:image"]').attr('content')
expect(ogImageHref).toContain('/base/another/opengraph-image.png')
})
} }
) )
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