Skip to content

Instantly share code, notes, and snippets.

@x-yuri
Last active March 23, 2025 07:38
Show Gist options
  • Save x-yuri/f4a2f1363ae5c08981c257cc406e00ac to your computer and use it in GitHub Desktop.
Save x-yuri/f4a2f1363ae5c08981c257cc406e00ac to your computer and use it in GitHub Desktop.
access.log for nextjs

access.log for nextjs

$ npx create-next-app app

app/Dockerfile:

FROM node:20.11.1-alpine3.19 as npm
COPY package*.json .
RUN npm install

FROM node:20.11.1-alpine3.19 as build
ENV NODE_ENV=production
WORKDIR /app
COPY --from=npm /node_modules node_modules
COPY . .
RUN npm run build

FROM node:20.11.1-alpine3.19
WORKDIR /app
COPY --from=build /app/public public
COPY --from=build /app/.next/standalone .
COPY --from=build /app/.next/static .next/static
# next 12.x
# RUN sed -Ei \
#     -e '/await handler/iconst __start = new Date;' \
#     -e '/await handler/aconsole.log(`-- [${__start.toISOString()}] ${((new Date - __start) / 1000).toFixed(3)} ${req.method} ${req.url}`);' \
#     server.js
# next 13.x, 14.x
RUN sed -Ei \
    -e '/await requestHandler/iconst __start = new Date;' \
    -e '/await requestHandler/aconsole.log(`-- [${__start.toISOString()}] ${((new Date - __start) / 1000).toFixed(3)} ${req.method} ${req.url}`);' \
    node_modules/next/dist/server/lib/start-server.js

app/.dockerignore:

.next
node_modules

Add output: 'standalone' to next.config.mjs.

$ docker build -t i app
$ docker run --rm -itp 3000:3000 i node server.js
$ curl localhost:3000
@m7kvqbe1
Copy link

Thanks!

@tomups
Copy link

tomups commented Mar 6, 2024

This was really helpful! I wrote a guide on how to do something similar by patching next.js on package install with patch-package, and using pino-http for well formatted and detailed JSON logging of requests and responses in case it helps somebody:

https://www.tomups.com/posts/log-nextjs-request-response-as-json/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment