Mastering Next.js: A Comprehensive Guide for React Developers
Usama Sarfraz
Software Engineer | MERN-STACK | FULL-STACK Web Developer | Typescript | React | GraphQL | Nest | AWS | Next
Hi, Before we start, here are some prerequisites for you to start reading this blog.
We expect you
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.
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 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.
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.
App Router:-
领英推荐
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.
App Router:-
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:-
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.
Software Engineer @Devigital Systems || Blockchain || Ethereum || Web3 || React.js || Next.js || Keystone.js
5 个月Interesting!
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!
Full Stack Developer | Expert in MERN( React--Node--Express--Mongodb)
6 个月Thanks for sharing
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.