Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 14 additions & 5 deletions packages/vinext/src/shims/metadata.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -831,12 +831,21 @@ function resolveSocialImageUrl(
metadataBase: URL | null | undefined,
): string {
const imageUrl = isSocialImageDescriptor(image) ? image.url : image;

// Next.js resolves social image URLs through resolveUrl(), which parses
// absolute strings before considering metadataBase. Returning the serialized
// URL also percent-encodes characters such as spaces in image paths.
if (imageUrl instanceof URL) {
return imageUrl.href;
}
try {
return new URL(imageUrl).href;
} catch {
// Relative social image URLs are composed with metadataBase below.
}

const metadataRoute = isSocialImageDescriptor(image) && isMetadataRouteSocialImage(image);
if (
typeof imageUrl === "string" &&
!isAbsoluteOrProtocolRelativeUrl(imageUrl) &&
(!metadataBase || metadataRoute)
) {
if (!isAbsoluteOrProtocolRelativeUrl(imageUrl) && (!metadataBase || metadataRoute)) {
return resolveMetadataUrl(imageUrl, getSocialImageMetadataBaseFallback(metadataBase));
}
return resolveMetadataUrl(imageUrl, metadataBase);
Expand Down
23 changes: 23 additions & 0 deletions tests/features.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3024,6 +3024,29 @@ describe("MetadataHead rendering", () => {
expect(html).toContain('content="https://acme.com/og.png"');
});

// Ported from Next.js: packages/next/src/lib/metadata/resolvers/resolve-opengraph.test.ts
// https://github.com/vercel/next.js/blob/canary/packages/next/src/lib/metadata/resolvers/resolve-opengraph.test.ts
it.each([
["without metadataBase", undefined],
["with a cross-origin metadataBase", new URL("https://site.example")],
])("percent-encodes absolute social image URLs %s", (_scenario, metadataBase) => {
const imageUrl = "https://cdn.example/path/my image.webp";
const encodedImageUrl = "https://cdn.example/path/my%20image.webp";
const html = renderToStaticMarkup(
React.createElement(MetadataHead, {
metadata: {
metadataBase,
openGraph: { images: [imageUrl] },
twitter: { images: [{ url: imageUrl }] },
},
}),
);

expect(html).toContain(`property="og:image" content="${encodedImageUrl}"`);
expect(html).toContain(`name="twitter:image" content="${encodedImageUrl}"`);
expect(html).not.toContain(imageUrl);
});

it("normalizes root canonical metadataBase URLs without a trailing slash", () => {
// Ported from Next.js: test/e2e/app-dir/metadata-dynamic-routes/index.test.ts
// https://github.com/vercel/next.js/blob/canary/test/e2e/app-dir/metadata-dynamic-routes/index.test.ts
Expand Down
Loading