Reza Safari Blog
Published on

Tips for Working with Next.js - Part 3

Caution: Some of these tips have been deprecated due to the release of Next.js 13. Read the post about the changes here.

  • If you don't have a valid reason, don't use Axios. Good old Fetch does the job. It's better to use one less package.

  • Use SWR for fetching data on the client side. Also, use fallback for data that comes from the server.

  • For data that comes from the server and you want to pre-render it, make sure to write a sanitizer that removes extra data from it before rendering. You can use ( It takes a list that can be nested and an array of keys. The output is of the same list type, with the keys you provided removed from it.

  • If you're using Zustand, don't forget to implement Hydration. The original example on the Next.js website (

  • Limit the use of Optional Chaining, and wherever possible, put a quick question mark when accessing properties (x?.z?.y?.m). If you know the reason for it, mention it in a comment so that others understand.

  • Keep the methods return or render as small as logically possible. Create a method if possible that renders for you or create a separate file. Whatever seems more logical.

  • If a part of the website doesn't need server-side rendering (for example, showing the user's latest invoice number), be sure to dynamically import it and set SSR to false so that it's only loaded on the client side.

  • If you're working with scroll events, be sure to remove them during unmounting. (This applies to all events).

  • In the getStaticProps method, make sure to handle errors yourself; otherwise, it may prevent the build (errors like a product not existing or an incorrect address provided).

  • It's recommended to keep some values in the env for the staging environment to disable ISR and have a faster build. Enable it only for production.

  • If your site doesn't support dark mode, be sure to set the meta color-scheme and supported-color-schemes.

  • When using party town and also have gtag, be sure to include forward=dataLayer.push in the party town script.

  • In the next.config file, be sure to include security headers (

  • In the next.config file and the webpack configuration section, merge duplicate chunks (config.optimization.mergeDuplicateChunks = true).

  • Before going to production, check your packages with the duplicate-package-checker-webpack-plugin to ensure you're not loading duplicate packages.

  • When using getInitialProps in _app, by default, all your pages are SSR rendered. Some may think you can't have SSG pages anymore, which is not true. The solution is to put an empty getStaticProps method in pages that don't need SSR (for example, About Us or Terms), and return an empty prop. This way, that page becomes SSG, and its loading speed increases several times.