Next.js is an open source React framework that helps developers rapidly build high-performance web applications with excellent user experience and SEO benefits. It’s trusted by leading brands such as Netflix, Uber, and Starbucks.
In this blog post, we’ll share some steps you can take to improve your performance when using Next.js.
There are two ways you can do this code-splitting in Next.js.
Component-based splitting: It's possible to optimize even more on a component level. If your app has large components, you can split them into separate chunks. This means any components that are not critical or only render when the user interacts with the UI can be lazy loaded as needed.
We’ve tackled this before in our definitive guide to image optimization. Next.js comes with a powerful and flexible image optimization component that does all of this automatically. To improve your performance, here's a quick list of the ways Next.js helps optimize your images:
You could also optimize your CSS for improved performance. Next.js comes with built-in CSS support. We’ve addressed CSS-related best practices in our complete guide to optimizing CSS. Here’s a handy checklist to help you optimize your styles:
Next.js supports CSS Modules using the [name].module.css file naming convention. By using CSS Modules you can avoid css collisions and they can be imported anywhere in your application. In the example below if an error class existed in the global scope the CSS Module would take precedence.
For improved performance, static generation is the more effective option. In static generation, HTML is generated at build time and can be reused on each request. These pages need to be built only once and can be cached and served by CDNs without additional configuration, which increases the speed.
When you’re scaling your site, you sometimes need to create or update pages after your site is built. To use static generation on each page without rebuilding your entire site, you can use incremental static regeneration (ISR). When a page was pre-rendered at build time and is requested, the user will first see the cached version. In the meantime, Next.js will regenerate the page and, once the page is generated, invalidate the cache to show the updated page.
You can solve this problem by using edge middleware, which allows you to cache the data and serve it from the CDN edge network. You can extract personalized information from the visitor's cookies, like their previous shopping history, purchases, or browsing behavior, which the edge middleware then uses to rewrite the page. In combination with incremental static regeneration from Next.js, these new parameters for the page are fetched and cached at the edge, so that it can be served instantly to subsequent users. This allows for high-speed personalization without any performance cost.