Thursday, February 17th 2022
Next.js 12.1
Posted byWe're excited to release one of our most requested features with Next.js 12.1:
- On-demand ISR (Beta): Revalidate pages using
getStaticProps
instantly. - Expanded Support for SWC:
styled-components
, Relay, and more. next/jest
Plugin: Zero-configuration Jest support using SWC.- Faster Minification with SWC (RC): 7x faster minification than Terser.
- Self-Hosting Improvements: ~80% smaller Docker images.
- React 18 & Server Components (Alpha): Improved stability and support.
- Developer Survey: Help us improve Next.js with your feedback.
Update today by running npm i next@latest
.
On-demand Incremental Static Regeneration (Beta)
Next.js now exposes a function unstable_revalidate()
allowing you to revalidate individual pages that use getStaticProps
. This was one of our most requested features since we introduced Incremental Static Regeneration (ISR) in Next.js 9.5.
Since ISR was released, we've seen companies like Tripadvisor, Parachute, HashiCorp, and more drastically improve their build times while retaining incredible performance. However, we've heard your feedback on interval-based revalidations and are excited to provide more flexibility.
Currently, if you set a revalidate
time of 60
, all visitors will see the same generated version of your site for one minute. The only way to invalidate the cache was from someone visiting that page after the minute had passed. You can now manually purge the Next.js cache for a specific page on-demand.
This makes it easier to update your site when:
- Content from your headless CMS is created or updated
- Ecommerce metadata changes (price, description, category, reviews, etc.)
export default async function handler(req, res) {
// Check for secret to confirm this is a valid request
if (req.query.secret !== process.env.MY_SECRET_TOKEN) {
return res.status(401).json({ message: 'Invalid token' });
}
try {
await res.unstable_revalidate('/path-to-revalidate');
return res.json({ revalidated: true });
} catch (err) {
// If there was an error, Next.js will continue
// to show the last successfully generated page
return res.status(500).send('Error revalidating');
}
}
Inside getStaticProps
, you do not need to specify revalidate
to use on-demand revalidation. If revalidate
is omitted, Next.js will use the default value of false
(no revalidation) and only revalidate the page on-demand when unstable_revalidate()
is called.
Incremental Static Regeneration works for any providers supporting the Next.js Build API (next build
). Starting today when deployed to Vercel, on-demand revalidation propagates globally in ~300ms when pushing pages to the edge.
View our demo to see on-demand revalidation in action and provide feedback. Svix (enterprise-ready webhooks) and Clerk (authentication) have also created a demo of on-demand ISR.
Improved SWC support
We want to make every Next.js application build faster for production and get instant feedback in local development. Next.js 12 introduced a new Rust-based compiler that takes advantage of native compilation.
With 12.1, we've added support to the Next.js Compiler for:
With the above six transforms added, we have now ported the most common Babel plugins to Rust using the new compiler. If there are other plugins you'd like to see, let us know on the discussion. Further, we're working on a system for high-performance WebAssembly plugins enabled through SWC.
Zero-configuration Jest plugin
Next.js now automatically configures Jest for you (next/jest
) using the Rust-based Next.js Compiler to transform files, including:
- Auto mocking stylesheets (
.css
,.module.css
, and their.scss
variants) and image imports - Loading
.env
(and all variants) intoprocess.env
- Ignoring
node_modules
from test resolving and transforms - Ignoring
.next
from test resolving - Loading
next.config.js
for flags that enable Next.js compiler transforms
Check out the documentation to learn more or get started from our Jest example.
Faster minification with SWC
With Next.js 12, we introduced minification using SWC as part of the Next.js Compiler. Early results showed it was 7x faster than Terser. Minification with SWC is now in Release Candidate (RC) with 12.1 and will become the default in 12.2.
You can opt-in to using SWC for minification in next.config.js
:
module.exports = {
swcMinify: true,
};
Let us know your feedback on the discussion.
Faster Image Optimization
The built-in Image Optimization API has been updated to support the same pattern as ISR pages, where images are served stale and revalidate in the background (also known as stale-while-revalidate
).
This is a significant performance improvement for optimizing images. See Image Caching Behavior to learn more.
Self-hosted Next.js improvements
Next.js can now automatically create a standalone
folder that copies only the necessary files for production deployments. This has resulted in ~80% smaller Docker images for self-hosted Next.js applications.
To leverage this automatic copying you can enable it in your next.config.js
:
module.exports = {
experimental: {
outputStandalone: true,
},
};
This will create a folder at .next/standalone
which can then be deployed on its own without installing node_modules
.
Check out the documentation or get started from the Docker example. We now also have a multi-env Docker example with support for loading different .env
files based on the environment.
React 18, Server Components, and SSR Streaming (Alpha)
As shown at Next.js Conf, we've been working to bring React 18, Server-Side Suspense, Streaming SSR, and eventually Server Components to Next.js.
Server Components are a new feature in React that let you reduce your JavaScript bundle size by separating server and client-side code. Server Components allow developers to build apps that span the server and client, combining the rich interactivity of client-side apps with the improved performance of traditional server rendering.
For developers following along on the Server Components path from alpha to beta in Next.js, here are some of the recent updates:
- Inline Server Component responses in the HTML to avoid a second request
- Improved script loading when streaming to enable partial hydration with React 18
- Support for the new
useId
API in React 18 - Support for
_app
as a Server Component - Improved code splitting for Server Components
- Improved streaming performance
- Ability to change the default runtime between Node.js and Edge (RFC)
We're working to enable you to run your entire Next.js application server-rendered at the Edge. You can choose which pages should opt into the Edge Runtime, so you can incrementally migrate pages from Node.js as you're ready.
We'll be releasing another post going more in-depth on the Edge Runtime soon. Both of our demos (next-server-components and next-rsc-demo) have been updated with the latest changes.
Other bug fixes and improvements
- Using
<a>
withtarget="blank"
no longer warns to usenext/link
with ESLint. .d.ts
files are no longer considered Pages.document.title
now takes priority overh1
when announcing page changes to screen readers.- Creating
pages/index/[...dynamic].js
now works, which previously was not possible due toindex
being a reserved keyword. - When using
dynamic(() => import('./some-component'), { ssr: false })
the import will be automatically treeshaken from the server code. - To create a smaller installation size and improve security, we're working to precompile more dependencies. The latest addition was
node-fetch
. - Improvements for Fast Refresh when using Middleware.
- Support for ESLint 8 with our built-in ESLint Integration.
styled-jsx
has been upgraded to 5.0, including new helpful error links for allstyled-jsx
compilation errors.- Edge Runtime: Support for
AbortController
andAbortSignal
- Edge Runtime:
CryptoKey
andglobalThis.CryptoKey
added. - Large Next.js applications are seeing ~60% improvements on Fast Refresh times with recent improvements (over 1,000 modules being reloaded).
- A notification is now shown if Fast Refresh fails and causes a full page reload.
- Announced routes now correctly skip announcing the initial page load when using React 18 strict mode.
- We have lowered the number of open issues by almost 300 on the Next.js repository compared to December 2021 (resolved almost 1000 issues).
Next.js Developer Survey
Share your feedback and help us improve Next.js with our first Developer Survey.
There are two parts to this survey: a quick survey of eight questions and an extended survey that dives into feedback for individual features. We'd love it if you could fill out both sections if you have time, but if not, feel free to submit your answers after the first section.
Your answers will be completely anonymous, though you can choose to share your app URLs with us if you like.
Thanks for helping us improve Next.js!
Thank you, contributors
Next.js is the result of the combined work of over 2,000 individual developers, industry partners like Google and Facebook, and our core team.
To make contribution easier, we've migrated the Next.js repository to use Turborepo to improve build performance. We've also added scaffolding for tests and error links to make it easier to get started writing tests. Finally, we recorded a 40-minute walkthrough video showing how to contribute to Next.js.
This release was brought to you by the contributions of: @MaedahBatool, @mutebg, @sokra, @huozhi, @hanford, @shuding, @sean6bucks, @jameshfisher, @devknoll, @yuta-ike, @zh-lx, @amandeepmittal, @alunyov, @stefanprobst, @leerob, @balazsorban44, @kdy1, @brittanyrw, @jord1e, @kara, @vvo, @ismaelrumzan, @dlindenkreuz, @MohammadxAli, @nguyenyou, @thibautsabot, @hanneslund, @vertti, @KateKate, @stefee, @mikinovation, @Leticijak, @mohsen1, @ncphillips, @ehowey, @lancechentw, @krychaxp, @fmacherey, @pklawansky, @RyanClementsHax, @lakbychance, @sannajammeh, @oliviertassinari, @alexander-akait, @u-yas, @Cheprer, @msp5382, @chrispat, @getspooky, @Ryz0nd, @klaasman, @midgleyc, @kumard3, @jesstelford, @neeraj3029, @glenngijsberts, @pie6k, @wouterraateland, @timneutkens, @11koukou, @thesyedbasim, @aeneasr, @ijjk, @lfades, @JuniorTour, @xavhan, @mattyocode, @padmaia, @Skn0tt, @gwer, @Nutlope, @styfle, @stipsan, @xhoantran, @eolme, @sespinosa, @zenorocha, @hjaber, @benmvp, @T-O-R-U-S, @dburrows, @atcastle, @kiriny, @molebox, @Vienio99, @kyliau, @PepijnSenders, @krystofex, @PizzaPete, @souljuse, @Schniz, @Nelsonfrank, @Mhmdrza, @hideokamoto-stripe, @Emrin, @gr-qft, @delbaoliveira, @redbar0n, @lxy-yz, @Divlo, @kachkaev, @teleaziz, @OgbeniHMMD, @goncy, @bennettdams, @hsynlms, @callumgare, @jonrosner, @karaggeorge, @rpie3, @MartijnHols, @bashunaimiroy, @NOCELL, @rishabhpoddar, @omariosouto, @theMosaad, @javivelasco, @pierrenel, @lobsterkatie, @tharakabimal, @saevarb, @nbouvrette, @paulnbrd, @ecklf, @renbaoshuo, @chozzz, @tbezman, @karlhorky, @j-mendez, @ffan0811, @arthurfiorette, @chimit, @joperron, @moh12594, @rasmusjp, @bryanrsmith, @TrySound, @josharsh, @thecrypticace, @arturparkhisenko, @segheysens, @thevinter, @AryanBeezadhur, @xiaohp, @tknickman, @oriolcp, @smakosh, @jorrit, @mix3d, @Clecio013, @michielvangendt, @intergalacticspacehighway, @jbraithwaite, @marcelocarmona, @benmerckx, @haykerman, @steven-tey, @jaredpalmer, @pi-guy-in-the-sky, @JuanM04, @apollisa, @D-Pagey, @Kikobeats, @ramosbugs, @dan-weaver, @chris-stytch, @MikevPeeren, @janpio, @emw3, @nubpro, @cmdcolin, @joostdecock, @sgallese, @housseindjirdeh, @minervabot, @cjboco, @Ryuurock, @dm430, @mkarkachov, @nvh95, @gfortaine, @zifeo, @vicente-s, @Rohithgilla12, @brookton, @skirsten, @davidfateh, @DavidBabel, @mannybecerra, @pveyes, @kaykdm, @xhiroga, @mzaien, @losfair, @ykzts, @knezevicdev, @yang-feng-yfeng, @xuchaobei, @elkevinwolf, @fabienheureux, @nilskaspersson, @Andarist, @mathcrln, @dferber90, @FranciscoMoretti, @benschwarz, @wendellhu95, @gazdagergo, @imabp, @ljosberinn, @samuliasmala, @ka2jun8, @monsonjeremy, @pqt, @leoortizz, @michel-kraemer, @ntkoopman, @iicdii, @chentsulin, @ericmatthys, @lennym, @balogunkeji, @wnr, @chemicalkosek, @KittyGiraudel, @OKinane, @KonstHardy, @BrandonRomano, @furcan, @dusanralic, @elliottsj, @hi-ogawa, @panva, @genetschneider, @thundermiracle, @stefano-rainieri, @ericbiewener, @vordgi, @stevejarvis, @ihmpavel, @matamatanot, @dyarfaradj, @iheyunfei, @ascorbic, @fytriht, @emzoumpo, @onurtemiz, @a-ursino, @mxschmitt, @bywo, @OArnarsson, @TurekBot, @gish, @vadymshymko, @kamsar, @skhaz, @Prashoon123, @IrisvanOllefen, @evan-bradley, @ntltd, @EzequielDM, @oBusk, @martpie, @BruceRodrigues, @luke-h1, @lucasvazq, @velocity23, @AkiraTsuboi, @mitheelgajare, @JamiesWhiteShirt, @leroydev, @JulienZD, @leotaku, @mattfwood, and @kripod.