Skip to content

Commit 782df6e

Browse files
authored
Add DEBUG mode (#46)
1 parent 61d9b91 commit 782df6e

File tree

6 files changed

+58
-24
lines changed

6 files changed

+58
-24
lines changed

README.md

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -294,9 +294,27 @@ Here's a link deployed using SST's [`NextjsSite`](https://docs.sst.dev/construct
294294

295295
## Debugging
296296

297-
To find the **server and image optimization** log, go to the AWS CloudWatch console in the **region you deployed to**.
297+
To find the **server and image optimization log**, go to the AWS CloudWatch console in the **region you deployed to**.
298298

299-
To find the **middleware** log, go to the AWS CloudWatch console in the **region you are physically close to**. For example, if you deployed your app to `us-east-1` and you are visiting the app from in London, the logs are likely to be in `eu-west-2`.
299+
To find the **middleware log**, go to the AWS CloudWatch console in the **region you are physically close to**. For example, if you deployed your app to `us-east-1` and you are visiting the app from in London, the logs are likely to be in `eu-west-2`.
300+
301+
#### Debug mode
302+
303+
You can run OpenNext in debug mode by setting the `OPEN_NEXT_DEBUG` environment variable:
304+
305+
```bash
306+
OPEN_NEXT_DEBUG=true npx open-next@latest build
307+
```
308+
309+
This does two things:
310+
311+
1. Lambda handler functions in the build output will not be minified.
312+
1. Lambda handler functions will automatically `console.log` the request event object along with other debugging information.
313+
314+
It is recommended to **turn off debug mode when building for production** because:
315+
316+
1. Un-minified function code is 2-3X larger than minified code. This will result in longer Lambda cold start times.
317+
1. Logging the event object on each request can result in a lot of logs being written to AWS CloudWatch. This will result in increated AWS costs.
300318

301319
## Opening an issue
302320

src/adapters/image-optimization-adapter.ts

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -18,8 +18,8 @@ import {
1818
ImageOptimizerCache,
1919
// @ts-ignore
2020
} from "next/dist/server/image-optimizer";
21-
2221
import { loadConfig } from "./util.js";
22+
import { debug } from "./logger.js";
2323

2424
const bucketName = process.env.BUCKET_NAME;
2525
const nextDir = path.join(__dirname, ".next");
@@ -31,7 +31,7 @@ const nextConfig = {
3131
...config.images,
3232
},
3333
};
34-
console.log("Init config", {
34+
debug("Init config", {
3535
nextDir,
3636
bucketName,
3737
nextConfig,
@@ -45,7 +45,7 @@ export async function handler(
4545
event: APIGatewayProxyEventV2
4646
): Promise<APIGatewayProxyResultV2> {
4747
// Images are handled via header and query param information.
48-
console.log("handler event", event);
48+
debug("handler event", event);
4949
const { headers: rawHeaders, queryStringParameters: queryString } = event;
5050

5151
try {
@@ -90,7 +90,7 @@ function validateImageParams(
9090
nextConfig,
9191
false
9292
);
93-
console.log("image params", imageParams);
93+
debug("image params", imageParams);
9494
if ("errorMessage" in imageParams) {
9595
throw new Error(imageParams.errorMessage);
9696
}
@@ -109,7 +109,7 @@ async function optimizeImage(
109109
false, // not in dev mode
110110
downloadHandler
111111
);
112-
console.log("optimized result", result);
112+
debug("optimized result", result);
113113
return result;
114114
}
115115

@@ -127,7 +127,7 @@ function buildSuccessResponse(result: any) {
127127
}
128128

129129
function buildFailureResponse(e: any) {
130-
console.error(e);
130+
debug(e);
131131
return {
132132
statusCode: 500,
133133
headers: {
@@ -147,7 +147,7 @@ async function downloadHandler(
147147
) {
148148
// downloadHandler is called by Next.js. We don't call this function
149149
// directly.
150-
console.log("downloadHandler url", url);
150+
debug("downloadHandler url", url);
151151

152152
// Reads the output from the Writable and writes to the response
153153
const pipeRes = (w: Writable, res: ServerResponse) => {

src/adapters/logger.ts

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
export function debug(...args: any[]) {
2+
if (process.env.OPEN_NEXT_DEBUG) {
3+
console.log(...args);
4+
}
5+
}

src/adapters/middleware-adapter.ts

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import type {
33
CloudFrontRequestResult,
44
CloudFrontHeaders,
55
} from "aws-lambda";
6+
import { debug } from "./logger.js";
67

78
// @ts-ignore
89
const index = await (() => import("./middleware.js"))();
@@ -12,9 +13,9 @@ export async function handler(
1213
): Promise<CloudFrontRequestResult> {
1314
const request = event.Records[0].cf.request;
1415
const { uri, method, headers, querystring, body } = request;
15-
console.log(uri);
16-
console.log(request);
17-
console.log(request.headers);
16+
debug(uri);
17+
debug(request);
18+
debug(request.headers);
1819

1920
// Convert CloudFront request to Node request
2021
// @ts-ignore Types has not been added for Node 18 native fetch API
@@ -44,7 +45,7 @@ export async function handler(
4445
const response = await index.default(nodeRequest, {
4546
waitUntil: () => {},
4647
});
47-
console.log("middleware response header", response.headers);
48+
debug("middleware response header", response.headers);
4849

4950
// WORKAROUND: Pass headers from middleware function to server function (AWS specific) — https://github.com/serverless-stack/open-next#workaround-pass-headers-from-middleware-function-to-server-function-aws-specific
5051
if (response.headers.get("x-middleware-next") === "1") {
@@ -78,7 +79,7 @@ function getMiddlewareRequestHeaders(response: any) {
7879
.forEach((key: string) => {
7980
headers[key] = response.headers.get(`x-middleware-request-${key}`);
8081
});
81-
console.log("getMiddlewareRequestHeaders", headers);
82+
debug("getMiddlewareRequestHeaders", headers);
8283
return JSON.stringify(headers);
8384
}
8485

@@ -89,7 +90,7 @@ function getMiddlewareResponseHeaders(response: any) {
8990
headers[key] = value;
9091
}
9192
});
92-
console.log("getMiddlewareResponseHeaders", headers);
93+
debug("getMiddlewareResponseHeaders", headers);
9394
return JSON.stringify(headers);
9495
}
9596

@@ -98,6 +99,6 @@ function httpHeadersToCfHeaders(httpHeaders: any) {
9899
httpHeaders.forEach((value: string, key: string) => {
99100
headers[key] = [{ key, value }];
100101
});
101-
console.log("httpHeadersToCfHeaders", headers);
102+
debug("httpHeadersToCfHeaders", headers);
102103
return headers;
103104
}

src/adapters/server-adapter.ts

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,12 +10,13 @@ import type {
1010
// @ts-ignore
1111
import NextServer from "next/dist/server/next-server.js";
1212
import { loadConfig } from "./util.js";
13+
import { debug } from "./logger.js";
1314

1415
setNextjsServerWorkingDirectory();
1516
const nextDir = path.join(__dirname, ".next");
1617
const config = loadConfig(nextDir);
1718
const htmlPages = loadHtmlPages();
18-
console.log({ nextDir });
19+
debug({ nextDir });
1920

2021
// Create a NextServer
2122
const requestHandler = new NextServer.default({
@@ -72,7 +73,7 @@ export async function handler(
7273
event: APIGatewayProxyEventV2,
7374
context: Context
7475
): Promise<APIGatewayProxyResultV2> {
75-
console.log(event);
76+
debug(event);
7677

7778
// WORKAROUND: Pass headers from middleware function to server function (AWS specific) — https://github.com/serverless-stack/open-next#workaround-pass-headers-from-middleware-function-to-server-function-aws-specific
7879
const middlewareRequestHeaders = JSON.parse(
@@ -98,7 +99,7 @@ export async function handler(
9899
);
99100
response.headers = { ...response.headers, ...middlewareResponseHeaders };
100101

101-
console.log("response headers", response.headers);
102+
debug("response headers", response.headers);
102103

103104
return response;
104105
}

src/build.ts

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -248,10 +248,12 @@ function createMiddlewareBundle(buildOutput: any) {
248248
// Save middleware code to file
249249
const src: string = buildOutput.output[middlewareName].files["index.js"].data;
250250
fs.writeFileSync(path.join(tempDir, "middleware.js"), src);
251-
fs.copyFileSync(
252-
path.join(__dirname, "adapters", "middleware-adapter.js"),
253-
path.join(tempDir, "middleware-adapter.js")
254-
);
251+
["middleware-adapter.js", "logger.js"].forEach((file) => {
252+
fs.copyFileSync(
253+
path.join(__dirname, "adapters", file),
254+
path.join(tempDir, file)
255+
);
256+
});
255257

256258
// Build Lambda code
257259
esbuildSync({
@@ -319,8 +321,15 @@ function esbuildSync(options: BuildOptions) {
319321
format: "esm",
320322
platform: "node",
321323
bundle: true,
322-
minify: true,
324+
minify: process.env.OPEN_NEXT_DEBUG ? false : true,
323325
...options,
326+
// "process.env.OPEN_NEXT_DEBUG" determins if the logger writes to console.log
327+
define: {
328+
...options.define,
329+
"process.env.OPEN_NEXT_DEBUG": process.env.OPEN_NEXT_DEBUG
330+
? "true"
331+
: "false",
332+
},
324333
});
325334

326335
if (result.errors.length > 0) {

0 commit comments

Comments
 (0)