# Nextjs - The Beginning

Next js is full stack framework.

Framework imposes very strict rules at every point, but libraries have a little free flow.

In framework, what is the name of folder, what extension you are naming the file, what is the file name. You have all restrictions on all these. You have to understand those rules that means framework.

In Next JS, you can give any name to folder but inside folder you cannot give any name to file. So you have to give that file name is *page.tsx*

In Nextjs, creating folders that will become your routes automatically. So, you do not need to install any frameworks or packages for routing. Like in react you have to install react-router package `npm i react-router` .

In Next js, if any page not found then by default next js provided a 404 not found page and also you can customize that page.

### 🚨Issue 1: Tailwind Dark Mode Error (Very Confusing 😵)

### ❌ What I Faced

In the latest Next.js setup:

- No `tailwind.config.ts` file
- Tried to write:

```css
@custom-variant dark (&:where(.dark, .dark *))
```

---

### 💥 Error I Got

```plaintext
CssSyntaxError: @custom-variant dark cannot have both a selector and a body
```

---

### 🔍 Why This Happened

Tailwind v4 introduced **config-less mode**, but:

👉 The syntax I used was WRONG\
👉 It must be written in block format

---

### ✅ How I Fixed It

```css
@import "tailwindcss";

@custom-variant dark {
  &:where(.dark, .dark *) {
    @slot;
  }
}
```

---

### 🧠 What I Learned

- Tailwind v4 uses **CSS-based configuration**
- `@custom-variant` must be written as a **block**
- `@slot` is mandatory
- Small syntax mistake = big error 😅

---

## 🚨 Issue 2: Tailwind Plugin Not Working

### ❌ What I Tried

I wrote a plugin to convert colors into CSS variables:

- Plugin to add each Tailwind color as a global CSS variable

```javascript
function addVariablesForColors({ addBase, theme }: any) {
  const allColors = flattenColorPalette(theme('colors'));
  const newVars = Object.fromEntries(
    Object.entries(allColors).map(([key, value]) => [`--${key}`, value])
  );

  addBase({
    ':root': newVars,
  });

```

But there was:\
👉 No `tailwind.config.ts` file

---

### 🤯 Problem

Tailwind v4 (config-less mode):

- ❌ Does NOT support plugins
- ❌ Does NOT support `theme()`
- ❌ Does NOT support `addBase`

---

### ✅ How I Fixed It

I created `tailwind.config.ts` manually:

```typescript
import type { Config } from "tailwindcss";
import flattenColorPalette from "tailwindcss/lib/util/flattenColorPalette";

function addVariablesForColors({ addBase, theme }: any) {
  const allColors = flattenColorPalette(theme("colors"));
  const newVars = Object.fromEntries(
    Object.entries(allColors).map(([key, value]) => [`--${key}`, value])
  );

  addBase({
    ":root": newVars,
  });
}

const config: Config = {
  darkMode: "class",
  content: [
    "./app/**/*.{js,ts,jsx,tsx}",
    "./components/**/*.{js,ts,jsx,tsx}",
  ],
  theme: {
    extend: {},
  },
  plugins: [addVariablesForColors],
};

export default config;
```

---

### 🧠 What I Learned

- Plugins **always require config file**
- Config-less mode is limited
- Real projects still use config

### Folder structure:

Every can have its own layout (layout.tsx) and page (page.tsx). Always follow the layout structure inside the folder.

Layout is a wrapper you can say is as a big box, a basic structure is there and this layout goes to every pages.

Page actually serves or delivers contents like in react create a layout file and keep all the things inside layout file, if you want navigation page on every page then we keep it inside layout file where you accept children.

If you create inner folder, then also follows same pattern which are mentioned above.

### **use client:**

Next js does not allow to use any of hooks of react directly. To use react hooks we need to add 'use client'. Now this 'use client' helps that this component use as client component because Next JS is a full stack framework, so many things are rendered on your server itself, but if you are doing any DOM manipulation then obviously it will be on the client side and all the hooks that react runs, they run on the client side. So, if you want to use any such hook, then you should write 'use client'

# Server and Client Components

By default, layouts and pages are [<u>Server Components</u>](https://react.dev/reference/rsc/server-components), which lets you fetch data and render parts of your UI on the server, optionally cache the result, and stream it to the client. When you need interactivity or browser APIs, you can use [<u>Client Components</u>](https://react.dev/reference/rsc/use-client) to layer in functionality.

### 1\. When to use Server and Client Components?

The client and server environments have different capabilities. Server and Client Components allow you to run logic in each environment depending on your use case.

Use **Client Components** when you need:

- [<u>State</u>](https://react.dev/learn/managing-state) and [<u>event handlers</u>](https://react.dev/learn/responding-to-events). E.g. `onClick`, `onChange`.
- [<u>Lifecycle logic</u>](https://react.dev/learn/lifecycle-of-reactive-effects). E.g. `useEffect`.
- Browser-only APIs. E.g. `localStorage`, `window`, `navigator.geolocation`, etc.
- [<u>Custom hooks</u>](https://react.dev/learn/reusing-logic-with-custom-hooks).

Use **Server Components** when you need:

- Fetch data from databases or APIs close to the source.
- Use API keys, tokens, and other secrets without exposing them to the client.
- Reduce the amount of JavaScript sent to the browser.
- Improve the [<u>First Contentful Paint (FCP)</u>](https://web.dev/fcp/), and stream content progressively to the client.

For example, the `<Page>` component is a Server Component that fetches data about a post, and passes it as props to the `<LikeButton>` which handles client-side interactivity.

`app/[id]/page.tsx`

```typescript
import LikeButton from '@/app/ui/like-button'
import { getPost } from '@/lib/data'

export default async function Page({
  params,
}: {
  params: Promise<{ id: string }>
}) {
  const { id } = await params
  const post = await getPost(id)

  return (
    <div>
      <main>
        <h1>{post.title}</h1>
        {/* ... */}
        <LikeButton likes={post.likes} />
      </main>
    </div>
  )
}
```

`app/ui/like-button.tsx`

```typescript
'use client'

import { useState } from 'react'

export default function LikeButton({ likes }: { likes: number }) {
  // ...
}
```

### 2\. How do Server and Client Components work in Next.js?

On the server, Next.js uses React's APIs to orchestrate rendering. The rendering work is split into chunks, by individual route segments ([<u>layouts and pages</u>](https://nextjs.org/docs/app/getting-started/layouts-and-pages)), including [<u>parallel route slots</u>](https://nextjs.org/docs/app/api-reference/file-conventions/parallel-routes) whether or not they are displayed:

- **Server Components** are rendered into a special data format called the React Server Component Payload (RSC Payload).
- **Client Components** and the RSC Payload are used to [<u>prerender</u>](https://nextjs.org/docs/app/glossary#prerendering) HTML.

**How Next.js Orchestrates Rendering:**

In Next.js, **orchestrating rendering** refers to **<mark>how the framework coordinates React's APIs across the server and the browser to turn your code into an interactive user interface</mark>**. Rather than rendering an entire page in a single pass, Next.js splits the work into smaller chunks and manages when and where each piece is processed.

When a user requests a page in the [**<u>Next.js App Router</u>**](https://nextjs.org/docs/app/getting-started/server-and-client-components), the framework coordinates the rendering lifecycle through several steps:

- **Splitting Work by Route Segments:**\
  Next.js divides the rendering work into chunks based on individual route segments, such as layouts, pages, and parallel route slots. This allows static shells and dynamic sections to coexist and resolve independently within a single response.
- **Generating the RSC Payload:**\
  On the server, Next.js uses React to render Server Components into <mark>a compact, serialized binary format</mark> called the React Server Component Payload (RSC Payload). This payload contains the <mark>rendered output of Server Components, props passed to Client Components</mark>, and placeholders marking where Client Components belong.
- **Prerendering Initial HTML:**\
  Next.js combines the <mark>RSC Payload with Client Component instructions to generate initial HTML on the server</mark>. This HTML is sent immediately to the browser to display a fast, non-interactive preview of the page.
- **Streaming Dynamic Content:**\
  If parts of a page rely on slow data fetches or dynamic request data, Next.js streams the initial static shell first. It then progressively sends the remaining HTML and RSC Payload chunks as each dynamic section finishes resolving.
- **Reconciling and Hydrating on the Client:**\
  Once the response reaches the browser, React uses the RSC Payload to reconcile (**Sync)** the server and client component trees and update the DOM. Finally, JavaScript attaches event listeners to Client Components in a process called <mark>hydration</mark>, making static HTML interface fully interactive.

  ```plaintext
  What is hydration?

  Hydration is React's process for attaching event handlers to the DOM, to make the static HTML interactive
  ```

**What is Reconciliing?**

In simple words, **reconcile** means **<mark>to compare two versions of something and resolve the differences so they match up properly</mark>**.

**What It Means in React?**

When React reconciles the <mark>server and client component trees</mark>, it acts like an editor comparing a newly received blueprint (the RSC Payload) against what is currently displayed on your screen. Instead of wiping out the entire page and rebuilding it from scratch, React figures out the exact pieces that changed, added, or moved, and only updates those specific parts in the browser's DOM. This preserves your current user state, such as text typed into an input box or scroll position.
