Next.js

A React framework that provides server-side rendering, static site generation, and other features for building production-ready web applications.

Overview

Next.js is a popular React framework that simplifies building full-stack web applications. It provides features like server-side rendering (SSR), static site generation (SSG), API routes, automatic code splitting, and optimized performance out of the box. Next.js is maintained by Vercel and has become one of the most popular ways to build React applications.

Example

javascript
// pages/index.js - Simple page
export default function Home() {
  return (
    <div>
      <h1>Welcome to Next.js!</h1>
    </div>
  );
}

// Dynamic routing: pages/posts/[id].js
export default function Post({ post }) {
  return <h1>{post.title}</h1>;
}

export async function getStaticProps({ params }) {
  const post = await fetchPost(params.id);
  return { props: { post } };
}

export async function getStaticPaths() {
  const posts = await fetchAllPosts();
  const paths = posts.map(post => ({
    params: { id: post.id.toString() }
  }));
  return { paths, fallback: false };
}

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

// App Router (Next.js 13+): app/page.tsx
export default function Page() {
  return <h1>App Router Page</h1>;
}

// Server Component with data fetching
async function getData() {
  const res = await fetch('https://api.example.com/data');
  return res.json();
}

export default async function Page() {
  const data = await getData();
  return <div>{data.title}</div>;
}

// next.config.js
module.exports = {
  images: {
    domains: ['example.com'],
  },
  reactStrictMode: true,
};

Key Features

  • Server-side rendering (SSR)
  • Static site generation (SSG)
  • API routes
  • File-based routing
  • Image optimization
  • TypeScript support

Key Points

  • Built on top of React
  • Hybrid static and server rendering
  • Excellent performance and SEO
  • Great developer experience
  • Deployed easily on Vercel

Learn More