Getting Started with Next.js
Learn the basics of building a web application with Next.js, including installation, pages, routing, and components.
Introduction to Next.js
Before diving into the technical setup, it's helpful to understand what makes Next.js different from Create React App and other frontend frameworks.
const features = ['SSR', 'API Routes', 'File-based routing'];
console.log(features.join(', '));
const features = ['SSR', 'API Routes', 'File-based routing'];
console.log(features.join(', '));
What is Next.js?
Next.js is a React-based framework for building server-rendered web applications. It simplifies routing, server-side rendering, and deployment.
npx create-next-app@latest my-next-app
cd my-next-app
npm run dev
npx create-next-app@latest my-next-app
cd my-next-app
npm run dev
Why Use Next.js?
Next.js provides an opinionated structure that works out of the box, supports both static and server rendering, and offers superior performance optimizations.
import Image from 'next/image';
<Image src='/logo.png' alt='Logo' width={100} height={100} />
import Image from 'next/image';
<Image src='/logo.png' alt='Logo' width={100} height={100} />
Core Concepts
Next.js simplifies routing and component reuse. By understanding pages, dynamic routes, and layouts, you'll have a solid foundation.
export async function getStaticProps() {
return { props: { data: 'static content' } };
}
export async function getStaticProps() {
return { props: { data: 'static content' } };
}
Pages and Routing
In Next.js, every file inside the `pages` directory automatically becomes a route. For example, `pages/about.tsx` maps to `/about`.
export default function About() {
return <h1>About Page</h1>;
}
export default function About() {
return <h1>About Page</h1>;
}
Linking Between Pages
Next.js uses the built-in `next/link` component to handle client-side navigation between pages.
import Link from 'next/link';
<Link href='/about'>
<a>Go to About</a>
</Link>
import Link from 'next/link';
<Link href='/about'>
<a>Go to About</a>
</Link>
Styling and Components
Next.js supports CSS Modules, Tailwind CSS, and other CSS-in-JS libraries like styled-components right out of the box.
import styles from './Home.module.css';
export default function Home() {
return <h1 className={styles.title}>Welcome</h1>;
}
import styles from './Home.module.css';
export default function Home() {
return <h1 className={styles.title}>Welcome</h1>;
}