Bytedance’s launch of Modern. Js was widely mocked by the Domestic FE community, and NextJS ushered in its 12th major version. Officials say this is the largest launch of NextJS ever. With such milestones, blogging is even more worthy of translation and memorization. Full free translation, if misleading, please give up reading.

The body of the

preface

As we announced in the next.js Conf, next.js 12 is our largest release ever:

  • Rust compiler: About three times faster Refresh and about five times faster build times
  • Middleware (Beta) : More flexibility in next.js by writing code rather than configuration
  • React 18 support: The native next.js API now supports React 18 features, including Suspense
  • AVIF support: Optionally reduce images by 20%
  • Bot-aware ISR Fallback: Optimized SEO to better support web crawlers
  • Native ES module support: alignment with standardized module systems
  • URL Import (alpha) : NPM packages can be imported through urls without installation
  • React Server Components (Alpha) : Try it now, including SSR Streaming feature

You can enjoy it today by running NPM I next@latest.

Rust Compiler – Faster fast refresh and build speed

We want each next.js application to build faster in production and get immediate feedback in local development. Next.js 12 includes a new Rust compiler that leverages the compilation capabilities of the native language.

Our Rust compiler is built on top of SWC, which is future-oriented and an open platform for efficient build tools. We optimized packaging and compilation, and fast Refresh was about three times faster in a local development environment and five times faster in a production environment. Other improvements and features include:

  • Speed up build of large Codebase: We have verified the compilation speed of Rust compilers with some of the largest next.js Codebase in the world.
  • Improved visibility of performance indicators: when Next. Js is compiled, the time nodes experienced by compilation, including the number of compiled modules and file names, will be printed to the browser and server console, so that developers can more intuitively see the improvement in compilation performance.
  • Underlying WebPack improvements: We have made several improvements to WebPack, including optimizing fast Refresh and making on-demand entries more reliable.

Compiling with Rust is 17 times faster than compiling with Babel. The default in NextJS V12 is to use the rust compiler to compile javaScript and typescript files. This means that we have to migrate the transformation capabilities of other Babel to Rust. In NextJS V12, a new CSS parser, written in RUST, is built in for the Styled – JSX translation.

The new Rust compiler is backward compatible. If your current project already has a Babel file, nextJS will fall back to compiling with Babel. We try to reuse your Babel configuration file, but use the Rust compiler to compile the current popular class libraries, such as Styled – Components, Emotion, relay. If you have a custom Babel configuration, please contribute your configuration file for testing.

The Rust compiler includes code compression, which is seven times faster than Terser. At this stage, code compression for the Rust compiler is optional (that is, you don’t have to use it), and we won’t remove this optional configuration until it is fully proven to work. It does so because it is replacing a lot of infrastructure that has existed for many years.

// next.config.js

module.exports = {
  swcMinify: true
}
Copy the code

In addition to hiring DongYoon Kang (SWC writer) and Maia Teegarden (Parcel code contributor), we will continue to invest in rust’s community. If you have experience with Rust development, please join us.

For more information, check out our demo at the Next. Js Conf conference.

The introduction of middleware

Middleware allows you to code freely instead of using configuration to achieve a purpose. This gives you complete flexibility in next.js because you can run the code before the request completes. Based on the user’s incoming request, you can modify the response by rewriting, redirecting, adding headers, or even streaming HTML.

Middleware can implement logical code sharing between a set of pages, including:

  • The authentication
  • Robot protection
  • Redirect and rewrite
  • Handle unsupported browsers
  • Functional labeling and A/B testing
  • Server-side analysis
  • Advanced I18N routing requirements
  • Call log
  • .

The middleware uses a strict Runtime to support standard Web apis such as FETCH. Out of the box by running Next Start, and out of the box by using Edge Functions in edge platforms such as Vercel.

To use middleware in next.js, you create the file pages/ _middleware.js. In this example, we use the standard Web API response (MDN) :

// pages/_middleware.js

export function middleware(req, ev) {
  return new Response('Hello, world! ')}Copy the code

For more information, watch the demo presented at the Next. Js Conf conference and review the documentation.

Prepare for the introduction of React 18

React 18 will add features like Suspense, automatic batch updates, the startTransition API and a new streaming API to support React. Lazy in server rendering environments.

We’ve been working closely with the React team at Facebook to prepare for the introduction of a stable version of React 18 in next.js. By using the pilot table flag bits, we can try these features out in NextJS 12 today.

$ npm install react@alpha react-dom@alpha
Copy the code

Server-Side Streaming

Concurrency features in React 18 include built-in support for Server-side Suspense and streaming SSR. This allows you to render pages using HTTP streams. This is an experimental feature in next.js 12, but once enabled SSR will use the same strict Runtime as middleware.

To enable, use the experimental flag bit concurrentFeatures: true:

// next.config.js
module.exports = {
  experimental: {
    concurrentFeatures: true}}Copy the code

React Server component

The React Server component allows us to render everything on the Server, including the components themselves. This is different from normal SSR with pre-generated HTML. With the server component, we can eliminate unnecessary client-side javascript code and render pages faster. This improves the user experience of the application while allowing you to reap the best of SSR and the rich interactivity of the client.

// next.config.js
module.exports = {
  experimental: {
    concurrentFeatures: true.serverComponents: true}}Copy the code

Next.js 12 allows you to make data requests at the component level, all expressed as JSX. By using the React Server Component, we keep things simple. With it, you no longer need special functions such as GetServerSideProps or GetStaticProps. This aligns with the React Hooks model you used earlier in the React Component to get and store data.

You can create the React Server Component by renaming a file in the Next. Js project page directory to.server.js and importing the Client Component directly into it. These client components will become interactive with hydrate, so you can add features like Upvotes.

We are currently working on Server-side Suspense, local Hydrate and streaming rendering and will share our progress in a future blog post.

Special thanks to our partner Kara Erickson and Gerald Monaco from the Google Aurora team for their work on React 18 and React Server Component.

For more information, see our demo at the Next. Js Conf conference and check out the documentation.

Native ES module support and URL import

The ES module brings an official, standardized module system to JavaScript. All major browsers and Node.js support them.

The standard pushes the Web ecosystem forward by supporting smaller package sizes and JavaScript bundles, ultimately leading to a better user experience. As the JavaScript ecosystem transitioned from Common JS (the old standard) to ES modules, we worked to help developers gradually adopt these improvements without making unnecessary disruptive changes.

Starting with next.js 11.1, we added experimental support for ES modules over CommonJS modules. In next.js 12, this is now the default setting. Of course, we still support importing NPM modules that only provide CommonJS packaging.

URL import

Next.js 12 includes experimental support for importing ES modules through urls without installation or separate build steps.

URL import allows you to use any package directly through the URL. This enables next.js to handle remote HTTP(S) resources as if they were local dependencies.

If a URL import is detected, Next. Js generates a Next. Lock file to track the remote resource. URL imports create a cache locally to ensure that you can still work offline. Next. Js supports URL import for both client and server.

If you want to experiment, you can add the corresponding allowed URL prefix configuration to the next.config.js configuration file:

module.exports = {
  experimental: {
    urlImports: ['https://cdn.skypack.dev']}}Copy the code

After that, you can import third-party modules in your module like this:

import confetti from 'https://cdn.skypack.dev/canvas-confetti'
Copy the code

Any CDN provider that supports hosting ES modules is supported, including some no-code platforms and design tools (e.g., Framer) :

  • Skypack
  • esm.sh
  • jsDelivr
  • JSPM
  • unpkg

For more information, see our demo at the Next. Js Conf conference and check out the documentation.

Robot sensing ISR (Incremental Static Regeneration) back

Currently, when you set fallback:true, ISR will render a Fallback status page on the first request for a particular page before the page is generated. If you want to block page rendering, you can use fallback: ‘blocking’.

In nextjs 12, web crawlers (e.g. search bots) automatically perform server-side ISR on pages that use fallback: true. While non-crawler clients still display the previous fallback status page, for crawler clients this prevents it from indexing the current Fallback page, because this is not what we (site owners) want.

Support AVIF – smaller size pictures

The built-in image optimization API now supports AVIF images, which are 20% smaller than WebP images.

AVIF images can take longer to optimize than WebP, so we use the new images.formats field in next.config.js to enable this feature:

module.exports = {
  images: {
    formats: ['image/avif'.'image/webp']}}Copy the code

This format list is used with the request Accept header to determine the image format that needs to be optimized. Since AVIF is the first in the list, it will be preferred if the browser supports AVIF. Otherwise, WebP will be provided if the browser supports it. If neither format is supported, the raw image format is provided.

Package the trace of input files

In next.js 8, we introduced the Target configuration item. This allows the pages in next.js to be exported as separate JavaScript packages by using WebPack to package all dependencies during build time. We quickly realized this wasn’t ideal and created @Vercel/NFT. @vercel/ NFT has been used in all deployments on the Vercel platform for over 2 years.

Now, by default, these optimizations are directly incorporated into the next.js framework for all deployment platforms, providing a significant improvement over the Target configuration item.

Next.js 12 automatically tracks which files are required for each page and API route using @Vercel/NFT, and prints these statistics Next to the console output of the Next Build command, allowing a third integrator to take advantage of the trace automatically provided by next.js.

These changes also optimize applications deployed using tools like Next Start + Docker. By using @vercel/ NFT, we can make the Next.js output independent in the future. You can run the application without installing any dependencies, greatly reducing the size of the Docker image.

The introduction of @vercel/ NFT into next.js replaces the target configuration item method, so the target configuration item is declared obsolete in next.js 12. See the documentation for more information.

Other optimization

  • Add a custompages/_app.jsorpages/_document.jsTo replace the two built-in files, now restart the Next development server.
  • Eslint, now integrated into NextJS 12, supports lint for specific files. Specifically in thenext lintOrder you to append later--fileParameters.
  • Nextjs 12 supports custom Settingstsconfig.jsonFile path.
  • next.config.mjsConfiguration files can be written as ES Module.
  • In-flight requests are now availablegetStaticPropsThe method is decoupled.
  • Now use a worker thread pool to check the static pages that are currently running.
  • Fast Refresh now uses WebSocket connections instead of EventSource connections.

Breaking Changes

  • With our default use of WebPack 5 after next.js 11, we announced that we have removed the use of WebPack 4 in next.js 12. We are now working closely with the community to ensure a smooth migration to WebPack 5.
  • next.config.jsIn thetargetConfiguration items are no longer required.
  • next/imageNow usespanAs a wrap element instead of being useddiv
  • The required nodeJS minimum version is already available from12.0.0Rise to12.22.0. nodejsv12.22.0Is the first version to support ES Moudle.

To learn more, check out our upgrade guide.

The last word

Five years ago, we released next.js to the public. We worked to build a zero-configuration React framework to simplify the experience for developers. Looking back, when we see where the community is today and what we can deliver to the community, it’s incredible. A better future awaits us. Let’s stay true to our roots and continue to forge ahead.

Next. Js is the result of more than 1,800 individual developers, industry partners like Google and Facebook, and our core team. Give them a round of applause.

Thanks to the following people who made this release possible: @ka2n, @housseindjirdeh, @rojserbest, @lobsterkatie, @thibautsabot, @javivelasco, @sokra, @rishabhpoddar, @kdy1, @huozhi, @georgegach, @ionut-botizan, @paul-creates, @TimBarley, @kimizuy, @devknoll, @matamatanot, @christianvuerings, @pgrodrigues, @mohamedbhy, @AlfonzAlfonz, @kara, @molebox, @angelopoole, @oste, @genetschneider, @jantimon, @kyliau, @mxschmitt, @PhattOZ, @finn-orsini, @kriswuollett, @harryheman, @GustavoEdinger, @AryanBeezadhur, @Blevs, @colevscode, @atcastle, @ijjk, @velocity23, @jonowu, @timneutkens, @whitep4nth3r, @micro-chipset, @TyMick, @padmaia, @arthurdenner, @vitorbal, @zNeb, @jacksonhardaker, @shuding, @kylemh, @Bundy-Mundi, @ctjlewis, @thien-do, @leerob, @Dev-CasperTheGhost, @janicklas-ralph, @rezathematic, @KonstHardy, @fracture91, @lorensr, @Sheraff, @HaNdTriX, @emilio, @oluan, @ddzieduch, @colinclerk, @x4th, @volcareso, @oiva, @sinchang, @scottrepreneur, @smakosh, @catnose99, @adrienharnay, @donsn, @andersonleite, @msp5382, @tim-hanssen, @appsplash99, @alexvilchis, @RobEasthope, @royal, @Perry-Olsson, @well-balanced, @mrmckeb, @buraksakalli, @espipj, @prateekbh, @AleksaC, @eungyeole, and @rgabs