How to debug getStaticProps (and getStaticPaths) in Next.js

Viewed 11002

I am trying to debug the getStaticProps() method of a React component included from my pages using console.log() like:

export default class Nav extends React.Component {
    render() {
        return <nav></nav>;
    }

    async getStaticProps() {
        console.log('i like output, though');
    }
}

However, I am neither able to see any output on the console from which the app is being served, nor on the browser's console. I also tried restarting yarn dev and running yarn build to see if it would produce output then. Alas, no cigar.

So what is the correct way to produce and read debug output from getStaticProps() and getStaticPaths()?

5 Answers

So after further research and testing I found out that getStaticProps() is only called on page components. So that was why I wasn't seeing any output. When I added the method to a component inside the pages directory I was able to see debug output produced with console.log() in the console running yarn dev on manual browser page refreshes (but not on automatic refreshes after modifying the page component) as well as during yarn build.

You can easily debug server-side code of your next application.

  1. To enable it you need to pass NODE_OPTIONS='--inspect' to your node processor. Best place to put it is in your package.json file where you run the app in dev mode => "dev": "NODE_OPTIONS='--inspect' next dev" .
  2. Now open a new tab in your chrome browser, and visit chrome://inspect. This will open chrome dev tool inspect where you can see your nextJs server under Remote Targets, Just click ìnspect. By clicking that it will open a new inspect window.
  3. Now simply put debugger inside your getStaticProps function and reload your client app, you will see the breakpoint in your server side code.

I hope this helps. Reference: https://nextjs.org/docs/advanced-features/debugging#server-side-code

Using the current next version (11.x) you can use console.log to print out any data in the getStaticProps() function.

You will see that output in the terminal where you run

   vercel dev

Your console.log will work but in the console of your app Terminal, not in the console in the browser. There you can check your message.

Also, if you get data [Object] then just in that console, make JSON.stringify(yourValue).

if it's a bigger object than stringify you can write like JSON.stringify(yourValue, null, 2) and it will be displayed within JSON way.

Related