How to log all routes in NextJS

Viewed 10746

I'm very new to NextJS - I currently have a pretty simple app that serves a handful of pages, and returns a 404 page if the route doesn't exist.

I'd like to get logging for every request, including pages that don't exist and return a 404 page. I'm running the app inside a docker container, or I'd like the logs to be written to stdout but not visible in chrome console out.

What's the best way to implement this?

2 Answers

This use-case sounds like an access-log setup.

The best way would be to setup a reverse proxy like nginx so it can create logs in your docker container.

If you don't want to do that, you can follow these two steps

  1. Setup a custom server that gets the request https://nextjs.org/docs/advanced-features/custom-server
  2. Use something like https://www.npmjs.com/package/next-bunyan to write out your logs

If you would like access from the front-end to be logged as well as they traverse the application - You could use something like a Google analytics account to capture both client and server side events.

If you're already on AWS and have your nextJS server running behind CloudFront you can easily enable request logging for the corresponding distribution and get this feature "free" without making any nextJS changes. This is also the most performant option IMHO.

Related