1. Difference Between NPX and NPM

  • NPM (Node Package Manager): Used to install packages globally or locally.
  • NPX (Node Package Execute): Executes packages without installing them globally.

2. Installation Process in Next.js

  • Using NPX: npx create-next-app@latest my-app
  • Using NPM: npm create next-app@latest my-app
  • Using Yarn: yarn create next-app my-app

During Installation:

  • Project Name
  • TypeScript or JavaScript
  • ESLint Configuration
  • Tailwind CSS
  • Src Directory Setup
  • Import Alias

3. Understanding the File System in Next.js

  • pages/ or app/ (routes and components)
  • public/ (static assets like images, fonts)
  • styles/ (CSS, Tailwind configurations)
  • components/ (Reusable UI components)
  • .next/ (Build output)

4. Server-side vs Client-side Scripting

  • Server-side: Runs on the backend (Node.js, Next.js API Routes)
  • Client-side: Runs in the browser (React components, events)

5. Function vs Component

  • Function: A reusable block of code that performs an operation.
  • Component: A UI element in React/Next.js that returns JSX.

6. Can React Code Work in Next.js?

  • Yes, but Next.js has additional features like server components and API routes.

7. Event Handling in Next.js

  • Runs on the client-side.
  • Use 'use client' when handling events.

8. Can Data Stored in a Component Be Used Outside of It?

  • No, unless passed as props or stored in a global state (e.g., Redux, Context API).

9. Difference Between State and Variable

  • Variable: Changes but does not trigger re-render.
  • State: Changes and triggers re-render.
import { useState } from 'react';
const Counter = () => {
    let count = 0;
    const [stateCount, setStateCount] = useState(0);

    return (
        <div>
            <p>Variable Count: {count}</p>
            <button onClick={() => count++}>Increase Variable</button>
            <p>State Count: {stateCount}</p>
            <button onClick={() => setStateCount(stateCount + 1)}>Increase State</button>
        </div>
    );
};
export default Counter;

10. Dependencies vs DevDependencies

  • Dependencies: Required for the app to run (react, next)
  • DevDependencies: Used only during development (eslint, babel)

11. Next.js Configurations

  • next.config.js: Configures Next.js behavior (rewrites, redirects, images, etc.)
  • jsconfig.json: Configures path aliases.

12. ESLint in Next.js

  • Used for code quality and best practices.
  • Run: npm run lint

13. .next Folder

  • Stores build output, optimized pages, and static assets.

14. Layout.js in Next.js

  • Defines the global layout for an app (e.g., header, footer, sidebar).

15. Types of Components in Next.js

  1. Server Components: Fetch data on the server.
  2. Client Components: Handle user interactions.
  3. Hybrid Components: Can use both.

Yes, we can use both client and server components in the same file using 'use client'.

16. Types of Rendering in Next.js

  1. Static Site Generation (SSG) - Pre-renders pages at build time.
  2. Server-side Rendering (SSR) - Generates pages dynamically on request.
  3. Client-side Rendering (CSR) - Fetches data on the client.
  4. Incremental Static Regeneration (ISR) - Updates static pages in the background.

17. Routing in Next.js

  • File-Based Routing: Routes are created automatically.
  • Example:
  • /pages/login.js/login
  • /pages/about.js/about
// pages/login.js
export default function Login() {
    return <h1>Login Page</h1>;
}

18. Linking and Navigation in Next.js

  • Use next/link or useRouter.
import Link from 'next/link';
const Home = () => (
    <Link href="/login">Go to Login</Link>
);
export default Home;
import { useRouter } from 'next/navigation';
const About = () => {
    const router = useRouter();
    return <button onClick={() => router.push('/login')}>Go to Login</button>;
};
export default About;

19. Nested Routing in Next.js

  • Example:
  • /pages/about/index.js/about
  • /pages/about/college.js/about/college

20. Dynamic Routing

  • Example: /pages/post/[id].js/post/123
import { useRouter } from 'next/router';
const Post = () => {
    const router = useRouter();
    return <h1>Post ID: {router.query.id}</h1>;
};
export default Post;

21. 404 Page in Next.js

  • Create pages/404.js
export default function Custom404() {
    return <h1>404 - Page Not Found</h1>;
}

22. Middleware in Next.js

  • Middleware intercepts requests before reaching the page.
import { NextResponse } from "next/server";
export function middleware(request) {
    return NextResponse.redirect(new URL('/login', request.url));
}
export const config = {
    matcher: ['/about/:path*'],
};



🚀 Why Next.js Over React.js?

React.js is a UI library that requires additional setup for SSR (Server-Side Rendering) and SEO optimization. Next.js improves upon React by providing:

  • Pre-rendering (SSG & SSR) for better performance & SEO.
  • Automatic Code Splitting for smaller bundle sizes.
  • Built-in Routing System (no need for React Router).
  • API Routes to handle backend logic within the project.
  • Image Optimization via the next/image component.

⚡ Rendering in Next.js

Next.js offers different rendering methods:

  1. Pre-rendering (Static Generation & Server-side Rendering)
  2. Client-side Rendering (CSR)
  3. Incremental Static Regeneration (ISR)

1️⃣ Static Site Generation (SSG)

  • Pages are generated at build time.
  • Data is fetched during build and converted into HTML.
  • Fast & SEO-friendly but doesn't update until re-deploy.

Example: Static Generation

export async function getStaticProps() {
  const res = await fetch('https://dummyjson.com/users');
  const users = await res.json();
  return { props: { users } };
}

export default function UsersPage({ users }) {
  return (
    <div>
      <h1>Users List</h1>
      {users.map(user => (
        <p key={user.id}>{user.firstName}</p>
      ))}
    </div>
  );
}

Network Request in Inspect (SSG)

  1. Open Inspect > Network
  2. The HTML is already available; no extra API call after page load.

2️⃣ Server-Side Rendering (SSR)

  • Pages are generated at request time (each time a user visits).
  • Slower than SSG but always returns fresh data.

Example: Server-side Rendering

export async function getServerSideProps() {
  const res = await fetch('https://dummyjson.com/users');
  const users = await res.json();
  return { props: { users } };
}

Network Request in Inspect (SSR)

  1. Open Inspect > Network
  2. API request occurs on every page load.

3️⃣ Client-side Rendering (CSR)

  • The page loads first, then fetches data on the client-side.
  • Faster initial load but not great for SEO.

Example: Fetch Data in Client Component

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

export default function Users() {
  const [users, setUsers] = useState([]);

  useEffect(() => {
    fetch("https://dummyjson.com/users")
      .then(res => res.json())
      .then(data => setUsers(data.users));
  }, []);

  return (
    <div>
      <h1>Users List</h1>
      {users.map(user => (
        <p key={user.id}>{user.firstName}</p>
      ))}
    </div>
  );
}

🖼️ Image Optimization in Next.js

Next.js provides an optimized next/image component with:

  • Lazy Loading
  • Automatic Optimization
  • Responsive Sizing

Example: Using next/image

import Image from "next/image";
export default function Profile() {
  return <Image src="/profile.jpg" width={300} height={300} alt="Profile" />;
}

Difference Between <img> & next/image

Feature <img> (HTML) next/image Lazy Loading ❌ No ✅ Yes Optimization ❌ No ✅ Yes Responsive ❌ No ✅ Yes Configuring External Image Domains

In next.config.js:

module.exports = {
  images: {
    domains: ["example.com"],
  },
};

🔤 Font Optimization

Without Next.js (Google Fonts)

<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto">

👎 Extra request goes to Google on every page load.

With Next.js next/font (Better Performance)

import { Inter } from "next/font/google";
const inter = Inter({ subsets: ["latin"] });
export default function Home() {
  return <h1 className={inter.className}>Hello World</h1>;
}

Fonts load faster & reduce external requests.

📌 Metadata & SEO Optimization

Static Metadata

export const metadata = {
  title: "Home Page",
  description: "This is the home page description",
};

Dynamic Metadata

export async function generateMetadata({ params }) {
  return {
    title: `${params.productName} - Product Details`,
    description: `Details of ${params.productName}`,
  };
}

📜 Using <Script> Component

Unlike <script> tags in HTML, Next.js <Script> component improves performance.

Example:

import Script from "next/script";
export default function Details() {
  return (
    <div>
      <h1>User Location Page</h1>
      <Script src="/location.js" strategy="lazyOnload" />
    </div>
  );
}

lazyOnload ensures the script loads after the page has rendered.

🏗️ Next.js Build & Production

1. Development Build

npm run dev
  • Runs on localhost:3000

2. Production Build

npm run build
npm start
  • Generates optimized output in .next/

🌐 Static Site Generation (SSG) with Dynamic Routes

Generate Static Params

export async function generateStaticParams() {
  const res = await fetch("https://dummyjson.com/users");
  const users = await res.json();
  return users.map((user) => ({ userId: user.id.toString() }));
}

Complete SSG Example

export async function getStaticProps({ params }) {
  const res = await fetch(`https://dummyjson.com/users/${params.userId}`);
  const user = await res.json();
  return { props: { user } };
}

Run npm run build and check out/ directory for pre-rendered HTML.