The best way to control Claude Code, Codex and more from any computer or phone
| 1 | /** |
| 2 | * Next.js on an AWS Lambda Web Function: Next's own standalone server, no |
| 3 | * OpenNext. |
| 4 | * |
| 5 | * A Web Function is a long-lived Node server, so Next runs the way it does |
| 6 | * under `next start`: SSR, middleware, ISR background revalidation and |
| 7 | * `/_next/image` all happen in-process. The build: |
| 8 | * |
| 9 | * 1. runs the project's `next build` with `NEXT_PRIVATE_STANDALONE` set, so |
| 10 | * Next traces a self-contained server directory without a change to |
| 11 | * `next.config.*` |
| 12 | * 2. copies the S3 `cacheHandler` (`./cache-handler.ts`) into it, so every |
| 13 | * environment shares one ISR, fetch and image cache |
| 14 | * 3. installs `sharp` for Linux on Arm64, which Next's image optimizer needs |
| 15 | * 4. writes `serve-node.mjs`, which starts Next's server (as the generated |
| 16 | * `server.js` does) with the cache handler, listening on |
| 17 | * `AWS_LAMBDA_HTTP_ENDPOINT` |
| 18 | * 5. copies `public/` and `.next/static` into the server (the image |
| 19 | * optimizer reads local images from it) and gathers them for S3 |
| 20 | */ |
| 21 | import { createRequire } from "node:module"; |
| 22 | import { fileURLToPath } from "node:url"; |
| 23 | import * as Effect from "effect/Effect"; |
| 24 | import * as FileSystem from "effect/FileSystem"; |
| 25 | import * as Path from "effect/Path"; |
| 26 | import type { PlatformError } from "effect/PlatformError"; |
| 27 | import * as ChildProcess from "effect/process/ChildProcess"; |
| 28 | import type * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; |
| 29 | import * as Stream from "effect/Stream"; |
| 30 | import { logChildOutput } from "../core/ChildOutput.ts"; |
| 31 | import * as FrameworkCore from "../core/index.ts"; |
| 32 | |
| 33 | const fail = (message: string) => (cause: unknown) => |
| 34 | new FrameworkCore.FrameworkError({ framework: "nextjs", message, cause }); |
| 35 | |
| 36 | /** The entry the Web Function starts, inside the standalone app directory. */ |
| 37 | export const STANDALONE_SERVE_ENTRY_FILE_NAME = "serve-node.mjs"; |
| 38 | |
| 39 | /** The S3 cache handler's file name inside the standalone app directory. */ |
| 40 | export const STANDALONE_CACHE_HANDLER_FILE_NAME = "alchemy-cache-handler.mjs"; |
| 41 | |
| 42 | /** The directory of files uploaded to S3, under `.next`. */ |
| 43 | export const STANDALONE_ASSETS_DIRECTORY = "alchemy-assets"; |
| 44 | |
| 45 | /** |
| 46 | * Start Next's standalone server the way its generated `server.js` does, |
| 47 | * with the S3 cache handler and the address Lambda passes in |
| 48 | * `AWS_LAMBDA_HTTP_ENDPOINT`. |
| 49 | */ |
| 50 | export const makeStandaloneServeEntrySource = ( |
| 51 | nextConfig: Record<string, unknown>, |
| 52 | buildTime: number, |
| 53 | ) => `// Generated by @alchemy.run/frontend-frameworks/nextjs/aws — do not edit. |
| 54 | import { createRequire } from "node:module"; |
| 55 | import * as path from "node:path"; |
| 56 | import { fileURLToPath } from "node:url"; |
| 57 | |
| 58 | const require = createRequire(import.meta.url); |
| 59 | const dir = path.dirname(fileURLToPath(import.meta.url)); |
| 60 | |
| 61 | process.env.NODE_ENV = "production"; |
| 62 | // The archive's file times are normalized, so prerendered pages are dated |
| 63 | // by the build instead (see the cache handler). |
| 64 | process.env.ALCHEMY_NEXT_BUILD_TIME = "${buildTime}"; |
| 65 | process.chdir(dir); |
| 66 | |
| 67 | const endpoint = process.env.AWS_LAMBDA_HTTP_ENDPOINT ?? "127.0.0.1:3000"; |
| 68 | const separator = endpoint.lastIndexOf(":"); |
| 69 | const hostname = endpoint.slice(0, separator).replace(/^\\[(.*)\\]$/, "$1"); |
| 70 | const port = Number.parseInt(endpoint.slice(separator + 1), 10); |
| 71 | |
| 72 | const nextConfig = { |
| 73 | ...${JSON.stringify(nextConfig)}, |
| 74 | cacheHandler: path.join(dir, ${JSON.stringify(STANDALONE_CACHE_HANDLER_FILE_NAME)}), |
| 75 | }; |
| 76 | process.env.__NEXT_PRIVATE_STANDALONE_CONFIG = JSON.stringify(nextConfig); |
| 77 | |
| 78 | require("next"); |
| 79 | const { startServer } = require("next/dist/server/lib/start-server"); |
| 80 | |
| 81 | await startServer({ |
| 82 | dir, |
| 83 | isDev: false, |
| 84 | config: nextConfig, |
| 85 | hostname, |
| 86 | port, |
| 87 | allowRetry: false, |
| 88 | }); |
| 89 | `; |
| 90 | |
| 91 | /** Run a command to completion, forwarding its output. */ |
| 92 | const run = (cmd: string, args: ReadonlyArray<string>, cwd: string, env: Record<string, string>) => |
| 93 | Effect.scoped( |
| 94 | Effect.gen(function* () { |
| 95 | const child = yield* ChildProcess.make(cmd, [...args], { |
| 96 | cwd, |
| 97 | stdin: "ignore", |
| 98 | stdout: "pipe", |
| 99 | stderr: "pipe", |
| 100 | env, |
| 101 | }).pipe(Effect.mapError(fail(`Failed to spawn ${cmd} (is it on PATH?)`))); |
| 102 | // Build output becomes log records, so the process that renders logs |
| 103 | // shows it and in-process capture (a test runner's log file) sees it. |
| 104 | const forward = ( |
| 105 | stream: Stream.Stream<Uint8Array, PlatformError>, |
| 106 | name: "stdout" | "stderr", |
| 107 | ) => |
| 108 | stream.pipe( |
| 109 | Stream.decodeText, |
| 110 | Stream.splitLines, |
| 111 | Stream.runForEach((line) => logChildOutput(line, name)), |
| 112 | ); |
| 113 | const { exitCode } = yield* Effect.all( |
| 114 | { |
| 115 | exitCode: child.exitCode, |
| 116 | stdout: forward(child.stdout, "stdout"), |
| 117 | stderr: forward(child.stderr, "stderr"), |
| 118 | }, |
| 119 | { concurrency: "unbounded" }, |
| 120 | ).pipe(Effect.mapError(fail(`Failed reading the output of ${cmd} ${args.join(" ")}`))); |
| 121 | if (exitCode !== 0) { |
| 122 | return yield* fail(`${cmd} ${args.join(" ")} exited with code ${exitCode}`)(undefined); |
| 123 | } |
| 124 | }), |
| 125 | ); |
| 126 | |
| 127 | const resolveCacheHandlerPath = Effect.try({ |
| 128 | try: () => |
| 129 | fileURLToPath(import.meta.resolve("@alchemy.run/frontend-frameworks/nextjs/cache-handler")), |
| 130 | catch: fail( |
| 131 | 'Failed to resolve "@alchemy.run/frontend-frameworks/nextjs/cache-handler" — is the package built?', |
| 132 | ), |
| 133 | }); |
| 134 | |
| 135 | /** The version of `sharp` the project resolves, if any. */ |
| 136 | const projectSharpVersion = (root: string) => |
| 137 | Effect.sync(() => { |
| 138 | try { |
| 139 | const require = createRequire(`${root.replace(/\/+$/, "")}/package.json`); |
| 140 | const packageJson = require.resolve("sharp/package.json"); |
| 141 | return (require(packageJson) as { version: string }).version; |
| 142 | } catch { |
| 143 | return undefined; |
| 144 | } |
| 145 | }); |
| 146 | |
| 147 | /** Copy a directory's contents into another, if it exists. */ |
| 148 | const copyInto = (from: string, to: string) => |
| 149 | Effect.gen(function* () { |
| 150 | const fs = yield* FileSystem.FileSystem; |
| 151 | if (!(yield* fs.exists(from).pipe(Effect.orElseSucceed(() => false)))) return; |
| 152 | yield* fs.makeDirectory(to, { recursive: true }); |
| 153 | yield* fs.copy(from, to, { overwrite: true }); |
| 154 | }); |
| 155 | |
| 156 | export const buildStandalone = Effect.fn(function* (options: { |
| 157 | readonly root: string; |
| 158 | readonly cli: string; |
| 159 | readonly env: Record<string, string> | undefined; |
| 160 | }) { |
| 161 | const fs = yield* FileSystem.FileSystem; |
| 162 | const path = yield* Path.Path; |
| 163 | const { root } = options; |
| 164 | |
| 165 | const env = yield* Effect.sync(() => ({ |
| 166 | ...(process.env as Record<string, string>), |
| 167 | ...options.env, |
| 168 | NODE_ENV: "production", |
| 169 | // Next's switch for `output: "standalone"` when the config sets none. |
| 170 | NEXT_PRIVATE_STANDALONE: "true", |
| 171 | })); |
| 172 | yield* run("node", [options.cli, "build"], root, env); |
| 173 | const buildTime = yield* Effect.sync(() => Date.now()); |
| 174 | |
| 175 | const nextDir = path.join(root, ".next"); |
| 176 | const serverFilesPath = path.join(nextDir, "required-server-files.json"); |
| 177 | const serverFiles = yield* fs.readFileString(serverFilesPath).pipe( |
| 178 | Effect.flatMap((raw) => |
| 179 | Effect.try({ |
| 180 | try: () => |
| 181 | JSON.parse(raw) as { |
| 182 | config: Record<string, unknown> & { output?: string }; |
| 183 | relativeAppDir?: string; |
| 184 | }, |
| 185 | catch: fail(`Failed to parse ${serverFilesPath}`), |
| 186 | }), |
| 187 | ), |
| 188 | Effect.mapError(fail(`The next build produced no ${serverFilesPath}`)), |
| 189 | ); |
| 190 | if (serverFiles.config.output !== "standalone") { |
| 191 | return yield* fail( |
| 192 | `next.config sets output: "${serverFiles.config.output}". A Lambda Web Function runs Next's standalone server; remove output, or set it to "standalone".`, |
| 193 | )(undefined); |
| 194 | } |
| 195 | // In a monorepo Next traces from the workspace root, so the app sits |
| 196 | // below `.next/standalone` at its path relative to that root. |
| 197 | const appDir = path.join(nextDir, "standalone", serverFiles.relativeAppDir ?? ""); |
| 198 | if (!(yield* fs.exists(path.join(appDir, "server.js")).pipe(Effect.orElseSucceed(() => false)))) { |
| 199 | return yield* fail(`The next build produced no standalone server in ${appDir}`)(undefined); |
| 200 | } |
| 201 | |
| 202 | yield* fs |
| 203 | .copyFile(yield* resolveCacheHandlerPath, path.join(appDir, STANDALONE_CACHE_HANDLER_FILE_NAME)) |
| 204 | .pipe(Effect.mapError(fail("Failed to copy the S3 cache handler"))); |
| 205 | |
| 206 | // Next's image optimizer needs sharp built for the function's platform. |
| 207 | // Install it in an empty project (the standalone directory carries the |
| 208 | // app's package.json, which npm would try to resolve whole), then merge |
| 209 | // its node_modules into the server's. |
| 210 | const sharpVersion = yield* projectSharpVersion(root); |
| 211 | const sharpProject = yield* fs |
| 212 | .makeTempDirectory({ prefix: "alchemy-next-sharp-" }) |
| 213 | .pipe(Effect.mapError(fail("Failed to create a directory for sharp"))); |
| 214 | yield* fs |
| 215 | .writeFileString( |
| 216 | path.join(sharpProject, "package.json"), |
| 217 | JSON.stringify({ name: "alchemy-next-sharp", private: true }), |
| 218 | ) |
| 219 | .pipe(Effect.mapError(fail("Failed to prepare the sharp install"))); |
| 220 | yield* run( |
| 221 | "npm", |
| 222 | [ |
| 223 | "install", |
| 224 | "--no-package-lock", |
| 225 | "--no-audit", |
| 226 | "--no-fund", |
| 227 | "--os=linux", |
| 228 | "--cpu=arm64", |
| 229 | "--libc=glibc", |
| 230 | `sharp${sharpVersion ? `@${sharpVersion}` : ""}`, |
| 231 | ], |
| 232 | sharpProject, |
| 233 | env, |
| 234 | ); |
| 235 | yield* copyInto(path.join(sharpProject, "node_modules"), path.join(appDir, "node_modules")).pipe( |
| 236 | Effect.mapError(fail("Failed to add sharp to the standalone server")), |
| 237 | ); |
| 238 | yield* fs.remove(sharpProject, { recursive: true }).pipe(Effect.ignore); |
| 239 | |
| 240 | yield* fs |
| 241 | .writeFileString( |
| 242 | path.join(appDir, STANDALONE_SERVE_ENTRY_FILE_NAME), |
| 243 | makeStandaloneServeEntrySource(serverFiles.config, buildTime), |
| 244 | ) |
| 245 | .pipe(Effect.mapError(fail("Failed to write the Web Function entry"))); |
| 246 | |
| 247 | // Next's image optimizer loads local images (`public/`, and static |
| 248 | // imports under `/_next/static/media`) from its own server, which only has |
| 249 | // them when they are copied in, as Next's standalone docs describe. |
| 250 | yield* copyInto(path.join(root, "public"), path.join(appDir, "public")).pipe( |
| 251 | Effect.mapError(fail("Failed to copy public/ into the standalone server")), |
| 252 | ); |
| 253 | yield* copyInto(path.join(nextDir, "static"), path.join(appDir, ".next", "static")).pipe( |
| 254 | Effect.mapError(fail("Failed to copy .next/static into the standalone server")), |
| 255 | ); |
| 256 | |
| 257 | // S3 serves `public/` at the root and the build's hashed files under |
| 258 | // `/_next/static`. |
| 259 | const assets = path.join(nextDir, STANDALONE_ASSETS_DIRECTORY); |
| 260 | yield* fs.remove(assets, { recursive: true }).pipe(Effect.ignore); |
| 261 | yield* copyInto(path.join(root, "public"), assets).pipe( |
| 262 | Effect.mapError(fail("Failed to gather public/ for upload")), |
| 263 | ); |
| 264 | yield* copyInto(path.join(nextDir, "static"), path.join(assets, "_next", "static")).pipe( |
| 265 | Effect.mapError(fail("Failed to gather .next/static for upload")), |
| 266 | ); |
| 267 | |
| 268 | return { |
| 269 | distDirectory: nextDir, |
| 270 | clientDirectory: assets, |
| 271 | serverModules: [ |
| 272 | { name: path.relative(nextDir, path.join(appDir, STANDALONE_SERVE_ENTRY_FILE_NAME)) }, |
| 273 | ], |
| 274 | }; |
| 275 | }); |
| 276 | |
| 277 | export type StandaloneBuildRequirements = |
| 278 | | FileSystem.FileSystem |
| 279 | | Path.Path |
| 280 | | ChildProcessSpawner.ChildProcessSpawner; |