Mastering Next.js: A Comprehensive Guide for React Developers

Mastering Next.js: A Comprehensive Guide for React Developers

Hi, Before we start, here are some prerequisites for you to start reading this blog.

We expect you

  • Have prior knowledge of JavaScript, basic web development, and React.
  • have Node.js installed on your machine.

What is Next.js:-

Next.js is a popular open-source React framework, which means it is React indeed with only a few differences.

Next.js is based on React Babel and Webpack, which provides an out-of-the-box solution for server-side rendering (SSR) of React components.

  • Server-side Rendering: Next.js supports SSR. It collects data and renders each request every time you need to deliver a different view for various users. React does not allow server-side rendering by default, although it can be enabled
  • Configuration: Another difference between Rect and Next JS you should consider is configuration. React doesn’t offer great support for configuration. Unless you disconnect from the standard Create React App, you won’t be able to change the setups. Hence, you’ll need to use what’s already set up or configured in CRA’s read scripts. On the other hand, everything is configurable with Next.js. The NextJS templates allow you to configure files such as babelrc, jest.config , and eslintrc.
  • SEO: While it is a React-based framework, Next.js provides SEO advantages that React does not and solves the shortcomings and challenges that come with using React.
  • Current problem with React: The problem with React lies in its client-side rendering methodology. Rendering websites on the client means that initially a relatively empty HTML file is sent to the browser, along with JavaScript files to execute. By executing those JavaScript files, the browser renders the page’s content. Search engines cannot properly index websites because all the bots see in the first pass is an empty app shell with no content. The bots only see the actual content when the page fully renders. This delay affects SEO, particularly for websites with hundreds or thousands of pages that need indexing. Additionally, client-side rendering also leads to slower load times and poor site performance because fetching, parsing, and executing the JavaScript takes time. Next.js provides better SEO performance by rendering web pages on the server (server-side) instead of rendering in the browser (client-side). Server-side rendering allows search engine crawlers and bots to scan and index web pages, detect metadata, and properly understand the information a website contains.

By handling the rendering on the server instead of the client, Next.js gives websites faster loading speeds, which improves the First Contentful Paint (FCP) and other important Core Web Vitals that affect SEO.

Next.js improves the Total Blocking Time (TBT) of websites by splitting the JavaScript code the browser needs to download into smaller bundles. This makes it easier for the browser to parse, compile, execute, and download only the necessary code.

Create Next App:-

Enough theory, let’s dive into the code!

Similar to the react app we can create the next app using this command

npx create-next-app@latest project-name ?        

You now have a new directory called next-blog ( let’s assume this is the name of your project ). Let’s cd into it:

cd nextjs-blog        

Then, run the following command:

npm run dev        

This starts your Next.js app’s "development server" (more on this later) on port 3000. Let’s check to see if it’s working. Open https://localhost:3000 from your browser.

Project Structure:- Below is the overview of what the latest next.js app directory looks like.


  • app
  • App Router
  • pages
  • Pages Router
  • public
  • Static assets to be served
  • src
  • Optional application source folder

App Router:-

The Next.js App Router introduces a new model for building applications using React's latest features such as?

Server Components: can be rendered and optionally cached on the server.

Streaming with Suspense:?

Streaming allows you to break down the page's HTML into smaller chunks and progressively send those chunks from the server to the client.)?

Suspense?

( <Suspense> works by wrapping a component that performs an asynchronous action (e.g. fetch data), showing fallback UI (e.g. skeleton, spinner) while it's happening, and then swapping in your component once the action completes. ), and Server Actions.

import { Suspense } from "react";

import { PostFeed, Weather } from "./Components";

export default function Posts() {
  return (
    <section>
      <Suspense fallback={<p>Loading feed...</p>}>
        <PostFeed />
      </Suspense>

      <Suspense fallback={<p>Loading weather...</p>}>
        <Weather />
      </Suspense>
    </section>
  );
}
        

Page Router:-

The Pages Router is a file-system-based router built on the concept of pages. When a file is added to the pages directory, it's automatically available as a route.

In Next.js, a page is a React Component exported from a .js, .jsx, .ts, or .tsx file in the pages directory. Each page is associated with a route based on its file name.


Top-level files:

Top-level files are used to configure your application, manage dependencies, run middleware, integrate monitoring tools, and define environment variables.


  • next.config.js ( Configuration file for Next.js )
  • package.json
  • Project dependencies and scripts
  • instrumentation.ts
  • OpenTelemetry and Instrumentation file
  • middleware.ts
  • Next.js request middleware
  • .env
  • Environment variables
  • .env.local
  • Local environment variables
  • .env.production
  • Production environment variables
  • .env.development
  • Development environment variables
  • .eslintrc.json
  • Configuration file for ESLint
  • .gitignore ( Git files and folders to ignore )
  • next-env.d.ts
  • TypeScript declaration file for Next.js
  • tsconfig.json ( Configuration file for TypeScript )
  • jsconfig.json ( Configuration file for JavaScript )


Routing in Next:-

In Next.js routing works differently for both the page and the next router. Below is defined how a routing looks like for each router.

Index routes:-

Page Router:-

Example: If you create pages/dashboard.js that export a React component like below, it will be accessible at /dashboard.

export default function Dashboard(){ 
   return <div>dashboard</div>
 }        


The router will automatically route files named index to the root of the directory.

  • pages/index.js → /
  • pages/dashboard/index.js → /blog

App Router:-

  • app/page.js → /
  • app/dashboard/page.js → /blog

Nested routes:-

Page Router:- The router supports nested files. If you create a nested folder structure, files will automatically be routed in the same way still.

  • pages/blog/first-post.js → /blog/first-post
  • pages/dashboard/settings/username.js → /dashboard/settings/username

App Router:-

  • app/blog/first-post/page.js → /blog/first-post
  • app/dashboard/settings/username/page.js → /dashboard/settings/username

Pages with Dynamic Routes

Page Router:- Next.js supports pages with dynamic routes.?

For example, if you create a file called pages/posts/[id].js, then it will be accessible at posts/1, posts/2, etc.

App Router:-

if you create a file called app/posts/[id]/page.js, then it will be accessible at posts/1, posts/2, etc


Layout in Next:-

A layout is a UI that is shared between multiple routes. On navigation, layouts preserve state, remain interactive, and do not re-render. Layouts can also be nested.

You can define a layout by default exporting a React component from a layout.js file. The component should accept a children prop that will be populated with a child layout (if it exists) or a page during rendering.

App Router:-

For example, in the case of APP ROUTER, the layout will be shared with the /dashboard and /dashboard/settings pages:

Page Router:-

In the case of page router

import Navbar from "./navbar";
import Footer from "./footer";

export default function Layout({ children }) {
  return (
    <>
      <Navbar /> 
        <main>
               {children}
         </main> 
        
       <Footer />
    </>
  );
}

// components/layout.js        

Route Handlers:-

Additionally, Next.js has support for API Routes, which let you easily create an API endpoint as a Node.js serverless function.

App Router:-

Route Handlers allow you to create custom request handlers for a given route using the Web Request and Response APIs.

Route Handlers are defined in a route.js|ts file inside the app directory:

export const dynamic = 'force-dynamic' // defaults to auto 

export async function GET(request: Request) {} 

export async function POST(request: Request) {}

// app/api/route.ts        

Page Router:-

API routes provide a solution to build a public API with Next.js.

Any file inside the folder pages/api is mapped to /api/* and will be treated as an API endpoint instead of a page. They are server-side-only bundles and won't increase your client-side bundle size.

For example, the following API route returns a JSON response with a status code of 200:

import { NextApiRequest, NextApiResponse } from "next";

export default function handler(req: NextApiRequest, res: NextApiResponse) {
  if (req.method === GET) {
    return res.status(200).json({ message: "Hello from Next.js!" });
  }

  if (req.method === "POST") {
    // Process a POST request
  } else {
    // Handle any other HTTP method
  }
}

//pages/api/hello.ts        

Middleware:-

Middleware allows you to run code before a request is completed. Then, based on the incoming request, you can modify the response by rewriting, redirecting, modifying the request or response headers, or responding directly.

Middleware runs before cached content and routes are matched

middleware.ts

Middleware will be invoked for every route in your project. Given this, it's crucial to use matchers to precisely target or exclude specific routes. The following is the execution order:

There are two ways to define which paths Middleware will run on:

  • Custom matcher config
  • Conditional statements

Custom matcher config:-

matcher allows you to filter Middleware to run on specific paths.

export const config = { matcher: "/about/:path*" };

//You can match a single path or multiple paths with an array syntax:

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

// middleware.js        

Conditional statements:-

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

export function middleware(request: NextRequest) {

  if (request.nextUrl.pathname.startsWith("/about")) {
    return NextResponse.rewrite(new URL("/about-2", request.url));
  }

  if (request.nextUrl.pathname.startsWith("/dashboard")) {
    return NextResponse.rewrite(new URL("/dashboard/user", request.url));
  }
}

// middleware.ts        

Additional Features in Next 14:-

Client-side components:-

Client Components allow you to write interactive UI that is pre-rendered on the server and can use client JavaScript to run in the browser.

To use Client Components, you can add the React "use client" directive at the top of a file, above your imports.

"use client";
import { useState } from "react";

export default function Counter() {
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>Click me</button>
    </div>
  );
}        

That’s it!

In Summary, next is the icing on the cake as it is more SEO friendly, fast, and gives you great support for configuration. Ideal for projects where marketing is needed like e-commerce platforms or landing pages etc.

Zawar Mughal

Software Engineer @Devigital Systems || Blockchain || Ethereum || Web3 || React.js || Next.js || Keystone.js

5 个月

Interesting!

回复
Khalid Farhan

Building HoverConsole.com | Entrepreneur | Visionary

6 个月

Awesome Next.js guide! Love the breakdown of features (SSR, routing, etc.) for better development and SEO A must-read for React devs of all levels! Let's discuss!

Adil Faizan

Full Stack Developer | Expert in MERN( React--Node--Express--Mongodb)

6 个月

Thanks for sharing

Umer Shuja

Senior Full Stack Developer | React js | Next js | Node js | Express js | MongoDB

6 个月

Thank you for sharing your insightful blog on transitioning from React.js to Next.js. Your detailed explanations and practical examples make it an invaluable resource for developers looking to leverage the full potential of Next.js in their projects. Keep up the great work! I look forward to reading more of your posts and learning from your experiences.

回复

要查看或添加评论,请登录

Usama Sarfraz的更多文章

社区洞察

其他会员也浏览了