REACT Next.js

Next.js is a React framework that enables server-side rendering (SSR), static site generation (SSG), and API routes. It’s widely used for building fast and SEO-friendly web applications.

 

1. Install Next.js

Using create-next-app

npx create-next-app@latest my-next-app
cd my-next-app
npm run dev

Try It Now

 

2. Folder Structure

my-next-app/
│── pages/         # Page components (each file is a route)
│── components/    # Reusable UI components
│── public/        # Static assets (images, fonts)
│── styles/        # CSS and styles
│── next.config.js # Next.js config file
│── package.json   # Project dependencies

Try It Now

3. Creating Pages (Routing in Next.js)

Each file in the pages/ folder automatically becomes a route.

Basic Page (pages/index.js)

const Home = () => {
  return <h1>Welcome to Next.js! πŸš€</h1>;
};

export default Home;

Try It Now

  • URL: /

Adding a New Page (pages/about.js)

const About = () => {
  return <h1>About Page</h1>;
};

export default About;

Try It Now

  • URL: /about

4. Linking Between Pages

Use next/link for client-side navigation.

import Link from "next/link";

const Navbar = () => (
  <nav>
    <Link href="/">Home</Link>
    <Link href="/about">About</Link>
  </nav>
);

export default Navbar;

Try It Now

5. Fetching Data in Next.js

a. Server-Side Rendering (SSR)

Fetch data at request time using getServerSideProps.

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

  return { props: { post } };
}

const Page = ({ post }) => <h1>{post.title}</h1>;

export default Page;

Try It Now

  • Best for dynamic content that changes frequently.

b. Static Site Generation (SSG)

Pre-fetch data at build time using getStaticProps.

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

  return { props: { post } };
}

const Page = ({ post }) => <h1>{post.title}</h1>;

export default Page;

Try It Now

  • Best for blogs, marketing pages, and SEO.

c. Incremental Static Regeneration (ISR)

Update static content without rebuilding the entire site.

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

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

Try It Now

  • Great for frequently updated content (e.g., news, products).

6. API Routes in Next.js

Create serverless API endpoints inside pages/api/.

Example API Route (pages/api/hello.js)

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

Try It Now

  • URL: /api/hello

7. Styling in Next.js

a. Global CSS (styles/globals.css)

Import it inside _app.js:

import "../styles/globals.css";

Try It Now

b. CSS Modules (Component-Level Styling)

import styles from "../styles/Home.module.css";

const Home = () => <h1 className={styles.title}>Styled Title</h1>;

Try It Now

  • Scoped styles (no global conflicts).

c. Tailwind CSS (Optional)

Install Tailwind:

npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p

Try It Now

Configure tailwind.config.js:

module.exports = {
  content: ["./pages/**/*.{js,ts,jsx,tsx}", "./components/**/*.{js,ts,jsx,tsx}"],
  theme: { extend: {} },
  plugins: [],
};

Try It Now

Use Tailwind in components:

<h1 className="text-2xl font-bold text-blue-500">Hello, Tailwind!</h1>

Try It Now

8. Image Optimization (next/image)

Use next/image for automatic lazy loading and responsive images.

import Image from "next/image";
import myImage from "../public/image.jpg";

<Image src={myImage} alt="Example Image" width={500} height={300} />;

Try It Now

Optimized loading and automatic resizing.

9. Environment Variables

Store API keys in .env.local:

NEXT_PUBLIC_API_URL=https://api.example.com

Try It Now

Access it in Next.js:

const apiUrl = process.env.NEXT_PUBLIC_API_URL;

Try It Now

10. Deploying Next.js

a. Vercel (Recommended)

Vercel is the easiest way to deploy Next.js:

npm install -g vercel
vercel

Try It Now

b. Netlify

npm run build

Try It Now

Upload the .next folder to Netlify.

c. GitHub Pages

  • Use Static Export:
    next build && next export
    

    Try It Now

  • Deploy /out folder.