9 min read

Next.js 2022: Still the 'One True Love', Now Even 'Better'!

Next.js 2022: Still the 'One True Love', Now Even 'Better'!

Next.js 2022: “Same Bottle, New Wine”, Even Better Than Before!

Hello fellow coders! 👋 In 2021, we unboxed Next.js and “fell in love” with it for its top features like SSR, SSG, and Automatic Routing, right? But the “fun” doesn’t stop there. One year later, Next.js has “evolved” with many new “weapons” that are sure to make front-end developers “swoon”. This article will give a quick review of the most notable upgrades in Next.js for 2022.

What’s “Hot” in Next.js 2022?

The programming world has already mastered the “basics” of Next.js, but the 2022 version still brings new and surprising features. Let’s take a look at these terms and see how these solid improvements work!

1. Incremental Static Regeneration (ISR): The “Peak” of Flexibility! 🚀

Remember when using SSG (Static Site Generation) meant you had to rebuild the whole website whenever content was updated? “Slow as a turtle” 🐢, right? But with Incremental Static Regeneration (ISR), Next.js lets you update the content of static pages without rebuilding everything. “Cool”, right?

How does ISR work?

  • You specify a time (in seconds) to revalidate (recheck) the page.
  • When that time is up, the first request to the page triggers a background regeneration of that page.
  • While the page is regenerating, Next.js serves the old (stale) version of the page.
  • Once regeneration is complete, Next.js silently updates the page.

ISR allows us to handle dynamic data while maintaining the performance benefits of SSG, creating a perfect solution for websites that need both static and dynamic content.

Why use ISR?

Only updating specific pages instead of the entire website helps reduce build time and resource usage. This is really important when you’re running a large website with high traffic.

Example:

// pages/products/[id].tsx

export async function getStaticProps({ params }: { params: { id: string } }) {
  const product = await getProductById(params.id);

  return {
    props: {
      product,
    },
    revalidate: 60, // Revalidate every 60 seconds
  };
}

export async function getStaticPaths() {
  // fallback: blocking => The user will wait until the page is generated.
  // fallback: true => The user will see the fallback page while the page is being generated.
  // fallback: false => 404 not found.
  return { paths: [], fallback: "blocking" };
}

function ProductPage({ product }: { product: any }) {
  // ... render the product
}

export default ProductPage;

With revalidate: 60, the product page will automatically update every 60 seconds. How convenient is that?

Real-World Applications of ISR:

ISR is typically used for pages with content that updates fairly often but not every minute. Examples include personal blog pages, product images, or weather data displays.

2. Image Optimization: “Auto” Beautiful, “Auto” Fast! 🖼️

Next.js has gotten even better with automatic image optimization. The next/image component has been upgraded with the ability to:

  • Automatically resize images based on the device.
  • Convert images to the WebP format (if the browser supports it).
  • Lazy load images.

Just use the <Image> component, and no complicated configuration is needed—your images will automatically be optimized to look better, load faster, and be lighter!

Example:

import Image from "next/image";

function MyComponent() {
  return (
    <Image
      src="/my-awesome-image.jpg" // Next.js will automatically optimize this image
      alt="My Awesome Image"
      width={500}
      height={300}
      priority // prioritize loading
      placeholder="blur" // add a blur effect while the image loads
    />
  );
}

How next/image Works:

  • Lazy Loading: This mechanism allows images to load only when they’re visible in the viewport, improving page load times.
  • Image Formats: Uses WebP if supported by the browser, ensuring smaller file sizes and better quality than traditional image formats like JPEG or PNG.
  • Improved Resizing: Ensures that images are always appropriately sized for the user’s device, optimizing the user experience on mobile devices.

Benefits of Using next/image:

  • Significantly reduces the file size of images, improving page load time.
  • Saves bandwidth for users by only loading images appropriate for their device.
  • Saves time and effort in image optimization, allowing developers to focus more on app development.

3. Middleware: “Take Control” of Requests! 🤝

Middleware is a new “superpower” in Next.js that lets you run code before a request is processed. You can use Middleware to:

  • Redirect users based on location, cookies, or other headers.
  • Rewrite URLs.
  • Add security headers.
  • A/B testing.

How does Middleware work?

Middleware runs on the server, which gives you better control over the request handling process without reducing performance. You can use JavaScript to customize navigation based on the user’s request or any other conditions.

Example:

// middleware.ts

import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";

export function middleware(request: NextRequest) {
  const response = NextResponse.next();

  if (request.nextUrl.pathname.startsWith("/about")) {
    response.headers.set("x-middleware", "about");
  }

  if (request.nextUrl.pathname.startsWith("/dashboard")) {
    response.headers.set("x-middleware", "dashboard");
  }

  return response;
}

export const config = {
  matcher: ["/about/:path*", "/dashboard/:path*"],
};

Middleware lets you control requests more flexibly and powerfully than ever. Next.js, you’re awesome!

Real-World Applications of Middleware:

Middleware is a powerful tool for customizing HTTP requests in various ways, such as in the following examples:

  • Redirecting users before they access protected pages: This is especially useful for protecting sensitive resources that should only be accessible to authenticated users.
  • Rewriting URLs for better device compatibility: This ensures that URLs are processed consistently, reducing user inconvenience.
  • Adding security headers: A quick way to enhance security on your website and prevent common attacks like CORS.
  • A/B Testing: Choose different versions of the site based on location or user groups to optimize user experience by testing diverse versions.

How to Create Middleware in Next.js:

To create Middleware in a Next.js project, just create a middleware.js file at the root of the project.

touch middleware.js

Then, add custom functions to handle requests in the middleware.

export function middleware(request) {
  if (request.nextUrl.pathname.startsWith("/dashboard")) {
    if (!request.cookies.get("authorized")) {
      const url = request.nextUrl.clone();
      url.pathname = "/login";
      return NextResponse.redirect(url);
    }
  }
  return NextResponse.next();
}

Other Improvements

4. Automatic Static Optimization (ASE)

Automatic Static Optimization (ASE) automatically turns dynamic pages into static pages. This improves performance and reduces the number of requests to the server. ASE works automatically, so no complex configuration is required.

5. CSS Modules Support

Next.js 2022 makes CSS files more compact by transforming CSS modules into separate files. This helps reduce bandwidth usage when loading pages.

Example:

Using CSS Modules in a simple component:

import styles from "./Button.module.css";

function Button({ children }) {
  return <button className={styles.button}>{children}</button>;
}

export default Button;

6. Next.js Image Library

The Next.js Image library supports image optimization, reducing file sizes and improving page load speed. Simply use the Image component instead of the traditional HTML <img> tag.

Example:

import Image from "next/image";

function MyComponent() {
  return (
    <div>
      <h1>Welcome to our site</h1>
      <Image src="/about-us.png" alt="About Us" width={500} height={300} />
    </div>
  );
}

Setting Up a Next.js 2022 Project: “Still Easy as Pie” But…

Setting up a Next.js project is still as easy as in 2021:

npx create-next-app@latest my-next-app --typescript
cd my-next-app
npm run dev

However, you may notice some minor changes in the project structure, especially if you choose to use the App Router (which we’ll discuss later).

App Router: A New Way of Routing

Starting from version 12, Next.js introduced the App Router as a replacement for the Pages Router. App Router offers several new features like Nested Layouts, Parallel Routes, and more.

Advantages of App Router over Pages Router:

  • Nested Layouts help organize code better, making it easier to manage layouts across different pages.
  • Parallel Routes allow displaying multiple pages simultaneously under one specific URL.
  • File-based Routing automatically scans files in the app folder to define routes.

Example directory structure using App Router:

app/
├── about/
│   ├── page.tsx      // /about
│   └── layout.tsx   // Layout for /about
├── blog/
│   ├── [slug]/       // Custom route based on slug
│   │   └── page.tsx  // /blog/[slug]
│   └── layout.tsx   // Layout for /blog
├── (auth)/
│   ├── layout.tsx    // Layout for auth group
│   ├── login/
│   │   └── page.tsx  // /login
│   └── register/
│       └── page.tsx  // /register
├── (shop)/
│   ├── cart/
│   │   └── page.tsx  // /(shop)/cart
│   └── checkout/
│       └── page.tsx  // /(shop)/checkout
├── components        // Shared components
├── lib               // Utility functions
└── types             // Type definitions

Using Layouts in App Router:

// app/dashboard/layout.tsx
export default function DashboardLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <div>
      <h1>Dashboard</h1>
      {/* Sidebar, header, etc. */}
      <section>{children}</section>
    </div>
  );
}

Conclusion: Next.js is “Still Top-Notch”, “Even Cooler”!

Next.js continues to assert itself as a top framework for front-end developers. With significant improvements in 2022, Next.js makes web app development faster, smoother, and cooler than ever. If you haven’t “tried” Next.js yet, take the leap today! You won’t regret it! 😉

Other Suggestions

Webpack 5: Next.js 2022 uses Webpack 5 to improve build performance and support new features.

Automatic Static Optimization (ASE): This feature automatically turns dynamic pages into static pages to boost performance.

Fallback ISR: When using ISR, you can rely on fallback modes to serve the old version of the page while it is being revalidated.

Build improvements: Faster build times and reduced wait times during development.

References:

Wishing you all a relaxing and meaningful summer! 🎉🌞