logo

Next.js Introduction

Get started with Next.js, the React framework

Next.js Introduction

Next.js is a powerful React framework that provides many features out of the box.

Key Features

  • Server-Side Rendering (SSR)
  • Static Site Generation (SSG)
  • API Routes
  • File-based Routing
  • Built-in CSS Support
  • Image Optimization

Getting Started

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

File-based Routing

pages/
├── index.js          // Route: /
├── about.js          // Route: /about
├── blog/
│   ├── index.js      // Route: /blog
│   └── [slug].js     // Route: /blog/:slug
└── api/
    └── users.js      // API Route: /api/users

Pages and Components

// pages/index.js
import Head from 'next/head';

export default function Home() {
  return (
    <>
      <Head>
        <title>My Next.js App</title>
      </Head>
      <main>
        <h1>Welcome to Next.js!</h1>
      </main>
    </>
  );
}

Data Fetching

// Static Generation
export async function getStaticProps() {
  const data = await fetch('https://api.example.com/data');
  return {
    props: { data }
  };
}

// Server-side Rendering
export async function getServerSideProps() {
  const data = await fetch('https://api.example.com/data');
  return {
    props: { data }
  };
}

API Routes

// pages/api/hello.js
export default function handler(req, res) {
  res.status(200).json({ message: 'Hello from Next.js API!' });
}

Next.js makes building React applications easier and more powerful!