Static Pages Without JavaScript Using Next.js
Published Sep 4, 2021
Next.js isnāt a pure HTML static site generator since JavaScript is required for many interactive parts of the site.
Most people that visit your site stay there for one page, so we donāt have to incur a cost of the entire JavaScript runtime.
That said, if you have a page that doesnāt require JavaScript wouldnāt it be great if you could just remove it? You can do that thanks to a experimental Next.js feature.
I created a typical Next.js app using npx create-next-app --typescript and removed some of the cruft, so weāre left with basic styles.
I ran npm run build, and after npm start weāre greeted with a bundle size of 71.89 kB. If we look inside the Inspector we can see the JavaScript used to run this single page.
Thereās no JavaScript required on this page, so letās remove it. This requires us to export a config inside a page with the experimental unstable_runtimeJS option set to false.
export const config = {
unstable_runtimeJS: false
} After we build and open the page we can see the size is just 3 kB since thereās no JavaScript, and inside the Inspector thereās only static HTML.
If you have other pages everything works fine. Itās just going to download JavaScript when itās required which means we donāt get preloading.
Conclusion
Keep in mind this is experimental and only works in production, so if youāre in development everything might seem to work but remember the JavaScript wonāt work in production.
You canāt execute JavaScript on the page without injecting custom <script> tags into the rendered HTML as mentioned in the pull request, but for most static pages it works great.
If youāre interested in reducing the bundle size of your Next.js site for parts where you do use JavaScript, I wrote Reduce Next.js Bundle Size by Half.
Thanks for reading! šāāļø