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: draft mode env vars not available #97

Closed
wants to merge 3 commits into from
Closed
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
7 changes: 7 additions & 0 deletions .changeset/young-eyes-hang.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
"@opennextjs/cloudflare": patch
---

fix: draft mode env vars not available

In certain scenarios, Next.js expects to be able to access environment variables for draft/preview mode. These environment variables were not being exposed before, but are now exposed on process.env.
1 change: 1 addition & 0 deletions packages/cloudflare/env.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ declare global {
SKIP_NEXT_APP_BUILD?: string;
NEXT_PRIVATE_DEBUG_CACHE?: string;
__OPENNEXT_KV_BINDING_NAME: string;
__NEXT_PRERENDER_MANIFEST_PREVIEW_CONFIG?: string;
[key: string]: string | Fetcher;
}
}
Expand Down
12 changes: 10 additions & 2 deletions packages/cloudflare/src/cli/build/build-worker.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { Plugin, build } from "esbuild";
import { copyPrerenderedRoutes, getPrerenderManifest } from "./utils";
import { cp, readFile, writeFile } from "node:fs/promises";
import { existsSync, readFileSync } from "node:fs";
import { Config } from "../config";
import { copyPackageCliFiles } from "./patches/investigated/copy-package-cli-files";
import { copyPrerenderedRoutes } from "./utils";
import { fileURLToPath } from "node:url";
import { inlineEvalManifest } from "./patches/to-investigate/inline-eval-manifest";
import { inlineMiddlewareManifestRequire } from "./patches/to-investigate/inline-middleware-manifest-require";
Expand Down Expand Up @@ -46,8 +46,10 @@ export async function buildWorker(config: Config): Promise<void> {
});
}

const prerenderManifest = getPrerenderManifest(config);

// Copy over prerendered assets (e.g. SSG routes)
copyPrerenderedRoutes(config);
copyPrerenderedRoutes(config, prerenderManifest);

copyPackageCliFiles(packageDistDir, config);

Expand Down Expand Up @@ -98,6 +100,12 @@ export async function buildWorker(config: Config): Promise<void> {
"process.env.NEXT_RUNTIME": '"nodejs"',
"process.env.NODE_ENV": '"production"',
"process.env.NEXT_MINIMAL": "true",
...(prerenderManifest?.preview && {
// Used for Next.js Draft Mode internal variables - https://nextjs.org/docs/app/building-your-application/configuring/draft-mode
"process.env.__NEXT_PRERENDER_MANIFEST_PREVIEW_CONFIG": JSON.stringify(
JSON.stringify(prerenderManifest.preview)
),
}),
},
// We need to set platform to node so that esbuild doesn't complain about the node imports
platform: "node",
Expand Down
16 changes: 6 additions & 10 deletions packages/cloudflare/src/cli/build/utils/copy-prerendered-routes.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { NEXT_META_SUFFIX, SEED_DATA_DIR } from "../../constants/incremental-cache";
import { copyFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { copyFileSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { dirname, join } from "node:path";
import { Config } from "../../config";
import type { PrerenderManifest } from "next/dist/build";
import type { Config } from "../../config";
import type { PrerenderManifest } from "./get-prerender-manifest";
import { readPathsRecursively } from "./read-paths-recursively";

/**
Expand All @@ -13,19 +13,15 @@ import { readPathsRecursively } from "./read-paths-recursively";
* the incremental cache to determine whether an entry is _fresh_ or not.
*
* @param config Build config.
* @param manifest Prerender manifest.
*/
export function copyPrerenderedRoutes(config: Config) {
export function copyPrerenderedRoutes(config: Config, manifest: PrerenderManifest | null) {
console.log("# copyPrerenderedRoutes");

const serverAppDirPath = join(config.paths.standaloneAppServer, "app");
const prerenderManifestPath = join(config.paths.standaloneAppDotNext, "prerender-manifest.json");
const outputPath = join(config.paths.outputDir, "assets", SEED_DATA_DIR);

const prerenderManifest: PrerenderManifest = existsSync(prerenderManifestPath)
? JSON.parse(readFileSync(prerenderManifestPath, "utf8"))
: {};
const prerenderedRoutes = Object.keys(prerenderManifest.routes);

const prerenderedRoutes = Object.keys(manifest?.routes ?? {});
const prerenderedAssets = readPathsRecursively(serverAppDirPath)
.map((fullPath) => ({ fullPath, relativePath: fullPath.replace(serverAppDirPath, "") }))
.filter(({ relativePath }) =>
Expand Down
21 changes: 21 additions & 0 deletions packages/cloudflare/src/cli/build/utils/get-prerender-manifest.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { existsSync, readFileSync } from "node:fs";
import { Config } from "../../config";
import { PrerenderManifest } from "next/dist/build";
import { join } from "node:path";

/**
* Reads the prerender manifest from the Next.js standalone output.
*
* @param config Build config
*/
export function getPrerenderManifest(config: Config): PrerenderManifest | null {
const prerenderManifestPath = join(config.paths.standaloneAppDotNext, "prerender-manifest.json");

if (!existsSync(prerenderManifestPath)) {
return null;
}

return JSON.parse(readFileSync(prerenderManifestPath, "utf8"));
}

export type { PrerenderManifest };
1 change: 1 addition & 0 deletions packages/cloudflare/src/cli/build/utils/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
export * from "./ts-parse-file";
export * from "./copy-prerendered-routes";
export * from "./get-prerender-manifest";
13 changes: 12 additions & 1 deletion packages/cloudflare/src/cli/templates/worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { MockedResponse } from "next/dist/server/lib/mock-request";
import type { NextConfig } from "next";
import type { NodeRequestHandler } from "next/dist/server/next-server";
import Stream from "node:stream";
import type { __ApiPreviewProps } from "next/dist/server/api-utils";

const NON_BODY_RESPONSES = new Set([101, 204, 205, 304]);

Expand All @@ -27,14 +28,24 @@ const cloudflareContextALS = new AsyncLocalStorage<CloudflareContext>();

// Injected at build time
const nextConfig: NextConfig = JSON.parse(process.env.__NEXT_PRIVATE_STANDALONE_CONFIG ?? "{}");
const nextPreviewConfig: __ApiPreviewProps = JSON.parse(
process.env.__NEXT_PRERENDER_MANIFEST_PREVIEW_CONFIG ?? "{}"
);

let requestHandler: NodeRequestHandler | null = null;

export default {
async fetch(request, env, ctx) {
return cloudflareContextALS.run({ env, ctx, cf: request.cf }, async () => {
if (requestHandler == null) {
globalThis.process.env = { ...globalThis.process.env, ...env };
globalThis.process.env = {
__NEXT_PREVIEW_MODE_ID: nextPreviewConfig.previewModeId,
__NEXT_PREVIEW_MODE_ENCRYPTION_KEY: nextPreviewConfig.previewModeEncryptionKey,
__NEXT_PREVIEW_MODE_SIGNING_KEY: nextPreviewConfig.previewModeSigningKey,
...globalThis.process.env,
...env,
};

// Note: "next/dist/server/next-server" is a cjs module so we have to `require` it not to confuse esbuild
// (since esbuild can run in projects with different module resolutions)
// eslint-disable-next-line @typescript-eslint/no-require-imports
Expand Down