# Next.js – The React Framework for Production

### **Introduction**

Next.js is a powerful **React framework** that enables **server-side rendering (SSR)**, **static site generation (SSG)**, and **full-stack development** using JavaScript. Developed by **Vercel**, Next.js enhances React applications by improving performance, SEO, and scalability. It is widely used for building modern **web applications, static websites, e-commerce platforms, and enterprise-grade solutions**.

### **Why Use Next.js?**

Next.js is preferred over traditional React applications because of its:

* &#x20;**Improved Performance** – Optimized SSR, automatic static optimization, and image optimization.
* &#x20;**SEO Benefits** – Pages load faster with SSR and SSG, improving search engine rankings.
* &#x20;**Automatic Code Splitting** – Loads only the necessary code for each page.
* &#x20;**Hybrid Rendering Support** – Supports **Static Site Generation (SSG)**, **Server-Side Rendering (SSR)**, and **Incremental Static Regeneration (ISR)**.
* &#x20;**API Routes** – Enables back-end functionality directly within a Next.js project.
* &#x20;**Built-in CSS & Sass Support** – Styled-components, Tailwind CSS, and global styles are natively supported.
* &#x20;**Full-Stack Capabilities** – API routes enable Next.js to act as both a frontend and backend framework.

### **Core Features of Next.js**

#### **1. File-Based Routing**

Next.js uses a **file-system-based routing** approach, meaning pages are automatically mapped based on the files inside the `pages/` directory.

Example: Creating two pages – `index.js` and `about.js`.

```jsx
// pages/index.js
export default function Home() {
  return <h1>Welcome to Next.js!</h1>;
}

```

```jsx
// pages/about.js
export default function About() {
  return <h1>About Us</h1>;
}

```

**Result:**\
Visiting `/` will render `index.js`, and `/about` will render `about.js` without manually setting up routes.

#### **2. Server-Side Rendering (SSR)**

Next.js enables **server-side rendering**, which fetches data before rendering the page on the server.

Example of SSR using `getServerSideProps()`:

```jsx
export async function getServerSideProps() {
  const res = await fetch("https://jsonplaceholder.typicode.com/posts/1");
  const data = await res.json();
  
  return { props: { post: data } };
}

export default function Post({ post }) {
  return <h1>{post.title}</h1>;
}

```

**Best for:** Real-time data, dynamic pages, and personalized content.

#### **3. Static Site Generation (SSG)**

Next.js allows **pre-rendering pages at build time** using `getStaticProps()`.

Example of SSG with external API data:

```jsx
export async function getStaticProps() {
  const res = await fetch("https://jsonplaceholder.typicode.com/posts");
  const posts = await res.json();
  
  return { props: { posts } };
}

export default function Blog({ posts }) {
  return (
    <div>
      <h1>Blog Posts</h1>
      <ul>
        {posts.map((post) => (
          <li key={post.id}>{post.title}</li>
        ))}
      </ul>
    </div>
  );
}

```

**Best for:** Blogs, marketing pages, documentation, and dashboards.

#### **4. Incremental Static Regeneration (ISR)**

Next.js allows **updating static content without rebuilding the entire site** using ISR.

Example of ISR using `revalidate`:

```jsx
export async function getStaticProps() {
  const res = await fetch("https://jsonplaceholder.typicode.com/posts/1");
  const post = await res.json();

  return { props: { post }, revalidate: 10 }; // Revalidates every 10 seconds
}

export default function Post({ post }) {
  return <h1>{post.title}</h1>;
}

```

**Best for:** News websites, e-commerce stores, and content-heavy applications.

#### **5. API Routes – Full-Stack Capabilities**

Next.js allows you to create **backend functionality within the same project** using API routes.

Example of an API endpoint (`pages/api/hello.js`):

```jsx
export default function handler(req, res) {
  res.status(200).json({ message: "Hello from Next.js API!" });
}

```

Accessing `/api/hello` in the browser returns:

```json
{ "message": "Hello from Next.js API!" }
```

**Best for:** Handling authentication, working with databases, and processing forms.

#### **6. Built-in Image Optimization**

Next.js provides an optimized `<Image>` component for faster loading images.

Example of using the **next/image** component:

```jsx
import Image from "next/image";

export default function Profile() {
  return (
    <div>
      <h1>Profile Picture</h1>
      <Image src="/profile.jpg" width={200} height={200} alt="Profile Picture" />
    </div>
  );
}

```

**Benefits:** Automatic lazy loading, optimized image delivery, and better performance.

#### **7. Middleware for Custom Logic**

Middleware runs **before a request is completed**, allowing modifications like authentication checks.

Example: Redirecting users if not authenticated (`middleware.js`):

```jsx
import { NextResponse } from "next/server";

export function middleware(req) {
  const isAuthenticated = req.cookies.token;
  if (!isAuthenticated) {
    return NextResponse.redirect("/login");
  }
}

```

**Best for:** Authentication, logging, and request modifications.

### Next.js vs React.js

<table><thead><tr><th>Features</th><th>ReactJS</th><th>NextJS</th><th><select></select></th></tr></thead><tbody><tr><td>Rendering  </td><td>CSR (Client-Side)</td><td>SSR, SSG, ISR, CSR</td><td></td></tr><tr><td>SEO Optimization</td><td>No SEO (CSR)</td><td>SEO Friendly (SSR, SSG)</td><td></td></tr><tr><td>Routing</td><td>Manual (React Router)</td><td>File-based routing</td><td></td></tr><tr><td>Performance</td><td>Slower (CSR)</td><td>Faster with pre-rendering</td><td></td></tr><tr><td>API Handling</td><td>External APIs</td><td>Built-in API routes</td><td></td></tr></tbody></table>

### **Conclusion**

Next.js takes **React to the next level**, offering **server-side rendering, static site generation, and full-stack capabilities** out of the box. It is a great choice for developers looking to **build fast, SEO-friendly, and scalable web applications**. Whether you’re working on a **blog, e-commerce site, or enterprise solution**, Next.js provides the tools needed for modern web development.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://www.anandisheladiya.com/skills-and-experience/frontend/next.js-the-react-framework-for-production.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
