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.
{% src=âexperimental-feature.webpâ alt=âExperimental feature for removing client-side JavaScript in productionâ %}
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.
{% src=ânetwork-with-javascript.webpâ alt=âNetwork tab JavaScript bundle sizeâ %}
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.
{% src=âinspector-with-javascript.webpâ alt=âInspector tab with JavaScriptâ %}
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.
{% src=ânetwork-without-javascript.webpâ alt=âNetwork tab without JavaScriptâ %}
{% src=âinspector-without-javascript.webpâ alt=âInspector tab without JavaScriptâ %}
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! đââď¸