Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix Next.js dynamic and static OG images #6592

Merged
merged 18 commits into from
Dec 8, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
- Fix Next.js dynamic and static OG images. (#6592)
27 changes: 20 additions & 7 deletions src/frameworks/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@
/**
*
*/
export async function discover(dir: string, warn = true) {

Check warning on line 63 in src/frameworks/index.ts

View workflow job for this annotation

GitHub Actions / lint (20)

Missing return type on function
const allFrameworkTypes = [
...new Set(Object.values(WebFrameworks).map(({ type }) => type)),
].sort();
Expand Down Expand Up @@ -89,18 +89,19 @@
// Memoize the build based on both the dir and the environment variables
function memoizeBuild(
dir: string,
build: (dir: string, target: string) => Promise<BuildResult | void>,
build: Framework["build"],
deps: any[],

Check warning on line 93 in src/frameworks/index.ts

View workflow job for this annotation

GitHub Actions / lint (20)

Unexpected any. Specify a different type
target: string
) {
target: string,
context: FrameworkContext
): ReturnType<Framework["build"]> {
const key = [dir, ...deps];

Check warning on line 97 in src/frameworks/index.ts

View workflow job for this annotation

GitHub Actions / lint (20)

Unsafe spread of an `any` value in an array
for (const existingKey of BUILD_MEMO.keys()) {
if (isDeepStrictEqual(existingKey, key)) {
return BUILD_MEMO.get(existingKey);
return BUILD_MEMO.get(existingKey) as ReturnType<Framework["build"]>;
}
}
const value = build(dir, target);
const value = build(dir, target, context);
BUILD_MEMO.set(key, value);

Check warning on line 104 in src/frameworks/index.ts

View workflow job for this annotation

GitHub Actions / lint (20)

Unsafe argument of type `any[]` assigned to a parameter of type `string[]`
return value;
}

Expand All @@ -108,7 +109,7 @@
* Use a function to ensure the same codebase name is used here and
* during hosting deploy.
*/
export function generateSSRCodebaseId(site: string) {

Check warning on line 112 in src/frameworks/index.ts

View workflow job for this annotation

GitHub Actions / lint (20)

Missing return type on function
return `firebase-frameworks-${site}`;
}

Expand Down Expand Up @@ -174,7 +175,7 @@
`Hosting config for site ${site} places server-side content in region ${ssrRegion} which is not known. Valid regions are ${validRegions}`
);
}
const getProjectPath = (...args: string[]) => join(projectRoot, source, ...args);

Check warning on line 178 in src/frameworks/index.ts

View workflow job for this annotation

GitHub Actions / lint (20)

Missing return type on function
// Combined traffic tag (19 chars) and functionId cannot exceed 46 characters.
const functionId = `ssr${site.toLowerCase().replace(/-/g, "").substring(0, 20)}`;
const usesFirebaseAdminSdk = !!findDependency("firebase-admin", { cwd: getProjectPath() });
Expand Down Expand Up @@ -210,9 +211,9 @@
if (selectedSite) {
const { appId } = selectedSite;
if (appId) {
firebaseConfig = await getAppConfig(appId, AppPlatform.WEB);

Check warning on line 214 in src/frameworks/index.ts

View workflow job for this annotation

GitHub Actions / lint (20)

Unsafe assignment of an `any` value
firebaseDefaults ||= {};
firebaseDefaults.config = firebaseConfig;

Check warning on line 216 in src/frameworks/index.ts

View workflow job for this annotation

GitHub Actions / lint (20)

Unsafe assignment of an `any` value
} else {
const defaultConfig = await implicitInit(options);
if (defaultConfig.json) {
Expand All @@ -221,7 +222,7 @@
You can link a Web app to a Hosting site here https://console.firebase.google.com/project/${project}/settings/general/web`
);
firebaseDefaults ||= {};
firebaseDefaults.config = JSON.parse(defaultConfig.json);

Check warning on line 225 in src/frameworks/index.ts

View workflow job for this annotation

GitHub Actions / lint (20)

Unsafe assignment of an `any` value
} else {
// N.B. None of us know when this can ever happen and the deploy would
// still succeed. Maaaaybe if someone tried calling firebase serve
Expand Down Expand Up @@ -286,6 +287,12 @@
purpose !== "deploy" &&
(await shouldUseDevModeHandle(frameworksBuildTarget, getProjectPath()));

const frameworkContext: FrameworkContext = {
projectId: project,
site: options.site,
hostingChannel: context?.hostingChannel,
};

let codegenFunctionsDirectory: Framework["ɵcodegenFunctionsDirectory"];
let baseUrl = "";
const rewrites = [];
Expand All @@ -309,7 +316,8 @@
getProjectPath(),
build,
[firebaseDefaults, frameworksBuildTarget],
frameworksBuildTarget
frameworksBuildTarget,
frameworkContext
);
const { wantsBackend = false, trailingSlash, i18n = false }: BuildResult = buildResult || {};

Expand Down Expand Up @@ -351,7 +359,7 @@

const codebase = generateSSRCodebaseId(site);
const existingFunctionsConfig = options.config.get("functions")
? [].concat(options.config.get("functions"))

Check warning on line 362 in src/frameworks/index.ts

View workflow job for this annotation

GitHub Actions / lint (20)

Unsafe argument of type `any` assigned to a parameter of type `ConcatArray<never>`
: [];
options.config.set("functions", [
...existingFunctionsConfig,
Expand Down Expand Up @@ -397,7 +405,12 @@
frameworksEntry = framework,
dotEnv = {},
rewriteSource,
} = await codegenFunctionsDirectory(getProjectPath(), functionsDist, frameworksBuildTarget);
} = await codegenFunctionsDirectory(
getProjectPath(),
functionsDist,
frameworksBuildTarget,
frameworkContext
);

const rewrite = {
source: rewriteSource || posix.join(baseUrl, "**"),
Expand Down
6 changes: 4 additions & 2 deletions src/frameworks/interfaces.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,14 +52,15 @@ export type FrameworksOptions = HostingOptions &
export type FrameworkContext = {
projectId?: string;
hostingChannel?: string;
site?: string;
};

export interface Framework {
supportedRange?: string;
discover: (dir: string) => Promise<Discovery | undefined>;
type: FrameworkType;
name: string;
build: (dir: string, target: string) => Promise<BuildResult | void>;
build: (dir: string, target: string, context?: FrameworkContext) => Promise<BuildResult | void>;
support: SupportLevel;
docsUrl?: string;
init?: (setup: any, config: any) => Promise<void>;
Expand All @@ -80,7 +81,8 @@ export interface Framework {
ɵcodegenFunctionsDirectory?: (
dir: string,
dest: string,
target: string
target: string,
context?: FrameworkContext
) => Promise<{
bootstrapScript?: string;
packageJson: any;
Expand Down
60 changes: 54 additions & 6 deletions src/frameworks/next/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,13 @@ import {
validateLocales,
getNodeModuleBin,
} from "../utils";
import { BuildResult, FrameworkType, SupportLevel } from "../interfaces";
import {
BuildResult,
Framework,
FrameworkContext,
FrameworkType,
SupportLevel,
} from "../interfaces";

import {
cleanEscapedChars,
Expand Down Expand Up @@ -67,7 +73,7 @@ import {
APP_PATHS_MANIFEST,
ESBUILD_VERSION,
} from "./constants";
import { getAllSiteDomains } from "../../hosting/api";
import { getAllSiteDomains, getDeploymentDomain } from "../../hosting/api";
import { logger } from "../../logger";

const DEFAULT_BUILD_SCRIPT = ["next build"];
Expand Down Expand Up @@ -101,7 +107,11 @@ export async function discover(dir: string) {
/**
* Build a next.js application.
*/
export async function build(dir: string): Promise<BuildResult> {
export async function build(
dir: string,
target: string,
context?: FrameworkContext
): Promise<BuildResult> {
await warnIfCustomBuildScript(dir, name, DEFAULT_BUILD_SCRIPT);

const reactVersion = getReactVersion(dir);
Expand All @@ -110,10 +120,27 @@ export async function build(dir: string): Promise<BuildResult> {
process.env.__NEXT_REACT_ROOT = "true";
}

const env = { ...process.env };

if (context?.projectId && context?.site) {
const deploymentDomain = await getDeploymentDomain(
context.projectId,
context.site,
context.hostingChannel
);

if (deploymentDomain) {
// Add the deployment domain to VERCEL_URL env variable, which is
// required for dynamic OG images to work without manual configuration.
// See: https://nextjs.org/docs/app/api-reference/functions/generate-metadata#default-value
env["VERCEL_URL"] = deploymentDomain;
}
}

const cli = getNodeModuleBin("next", dir);

const nextBuild = new Promise((resolve, reject) => {
const buildProcess = spawn(cli, ["build"], { cwd: dir });
const buildProcess = spawn(cli, ["build"], { cwd: dir, env });
buildProcess.stdout?.on("data", (data) => logger.info(data.toString()));
buildProcess.stderr?.on("data", (data) => logger.info(data.toString()));
buildProcess.on("error", (err) => {
Expand Down Expand Up @@ -488,7 +515,12 @@ export async function ɵcodegenPublicDirectory(
/**
* Create a directory for SSR content.
*/
export async function ɵcodegenFunctionsDirectory(sourceDir: string, destDir: string) {
export async function ɵcodegenFunctionsDirectory(
sourceDir: string,
destDir: string,
target: string,
context?: FrameworkContext
): ReturnType<NonNullable<Framework["ɵcodegenFunctionsDirectory"]>> {
const { distDir } = await getConfig(sourceDir);
const packageJson = await readJSON(join(sourceDir, "package.json"));
// Bundle their next.config.js with esbuild via NPX, pinned version was having troubles on m1
Expand Down Expand Up @@ -558,9 +590,25 @@ export async function ɵcodegenFunctionsDirectory(sourceDir: string, destDir: st
packageJson.dependencies["sharp"] = SHARP_VERSION;
}

const dotEnv: Record<string, string> = {};
if (context?.projectId && context?.site) {
const deploymentDomain = await getDeploymentDomain(
context.projectId,
context.site,
context.hostingChannel
);

if (deploymentDomain) {
// Add the deployment domain to VERCEL_URL env variable, which is
// required for dynamic OG images to work without manual configuration.
// See: https://nextjs.org/docs/app/api-reference/functions/generate-metadata#default-value
dotEnv["VERCEL_URL"] = deploymentDomain;
}
}

await mkdirp(join(destDir, distDir));
await copy(join(sourceDir, distDir), join(destDir, distDir));
return { packageJson, frameworksEntry: "next.js" };
return { packageJson, frameworksEntry: "next.js", dotEnv };
}

/**
Expand Down
34 changes: 34 additions & 0 deletions src/hosting/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import * as operationPoller from "../operation-poller";
import { DEFAULT_DURATION } from "../hosting/expireUtils";
import { getAuthDomains, updateAuthDomains } from "../gcp/auth";
import * as proto from "../gcp/proto";
import { getHostnameFromUrl } from "../utils";

const ONE_WEEK_MS = 604800000; // 7 * 24 * 60 * 60 * 1000

Expand Down Expand Up @@ -551,6 +552,7 @@ export async function getSite(project: string, site: string): Promise<Site> {
if (e instanceof FirebaseError && e.status === 404) {
throw new FirebaseError(`could not find site "${site}" for project "${project}"`, {
original: e,
status: e.status,
});
}
throw e;
Expand Down Expand Up @@ -751,3 +753,35 @@ export async function getAllSiteDomains(projectId: string, siteId: string): Prom

return Array.from(allSiteDomains);
}

/**
* Get the deployment domain.
* If hostingChannel is provided, get the channel url, otherwise get the
* default site url.
*/
export async function getDeploymentDomain(
projectId: string,
siteId: string,
hostingChannel?: string | undefined
): Promise<string | null> {
if (hostingChannel) {
const channel = await getChannel(projectId, siteId, hostingChannel);

return channel && getHostnameFromUrl(channel?.url);
}

const site = await getSite(projectId, siteId).catch((e: unknown) => {
// return null if the site doesn't exist
if (
e instanceof FirebaseError &&
e.original instanceof FirebaseError &&
e.original.status === 404
) {
return null;
}

throw e;
});

return site && getHostnameFromUrl(site?.defaultUrl);
}
58 changes: 58 additions & 0 deletions src/test/hosting/api.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -821,6 +821,64 @@ describe("hosting", () => {
expect(nock.isDone()).to.be.true;
});
});

describe("getDeploymentDomain", () => {
afterEach(nock.cleanAll);

it("should get the default site domain when hostingChannel is omitted", async () => {
const defaultDomain = EXPECTED_DOMAINS_RESPONSE[EXPECTED_DOMAINS_RESPONSE.length - 1];
const defaultUrl = `https://${defaultDomain}`;

nock(hostingApiOrigin)
.get(`/v1beta1/projects/${PROJECT_ID}/sites/${SITE}`)
.reply(200, { defaultUrl });

expect(await hostingApi.getDeploymentDomain(PROJECT_ID, SITE)).to.equal(defaultDomain);
});

it("should get the default site domain when hostingChannel is undefined", async () => {
const defaultDomain = EXPECTED_DOMAINS_RESPONSE[EXPECTED_DOMAINS_RESPONSE.length - 1];
const defaultUrl = `https://${defaultDomain}`;

nock(hostingApiOrigin)
.get(`/v1beta1/projects/${PROJECT_ID}/sites/${SITE}`)
.reply(200, { defaultUrl });

expect(await hostingApi.getDeploymentDomain(PROJECT_ID, SITE, undefined)).to.equal(
defaultDomain
);
});

it("should get the channel domain", async () => {
const channelId = "my-channel";
const channelDomain = `${PROJECT_ID}--${channelId}-123123.web.app`;
const channel = { url: `https://${channelDomain}` };

nock(hostingApiOrigin)
.get(`/v1beta1/projects/${PROJECT_ID}/sites/${SITE}/channels/${channelId}`)
.reply(200, channel);

expect(await hostingApi.getDeploymentDomain(PROJECT_ID, SITE, channelId)).to.equal(
channelDomain
);
});

it("should return null if channel not found", async () => {
const channelId = "my-channel";

nock(hostingApiOrigin)
.get(`/v1beta1/projects/${PROJECT_ID}/sites/${SITE}/channels/${channelId}`)
.reply(404, {});

expect(await hostingApi.getDeploymentDomain(PROJECT_ID, SITE, channelId)).to.be.null;
});

it("should return null if site not found", async () => {
nock(hostingApiOrigin).get(`/v1beta1/projects/${PROJECT_ID}/sites/${SITE}`).reply(404, {});

expect(await hostingApi.getDeploymentDomain(PROJECT_ID, SITE)).to.be.null;
});
});
});

describe("normalizeName", () => {
Expand Down
11 changes: 11 additions & 0 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -799,3 +799,14 @@ export async function openInBrowserPopup(
},
};
}

/**
* Get hostname from a given url or null if the url is invalid
*/
export function getHostnameFromUrl(url: string): string | null {
try {
return new URL(url).hostname;
} catch (e: unknown) {
return null;
}
}
Loading