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
npm run dev
starts the development server at http://localhost:3000.
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
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;
- URL:
/
Adding a New Page (pages/about.js)
const About = () => { return <h1>About Page</h1>; }; export default About;
- 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;
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;
- 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;
- 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 }
- 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!" }); }
- URL:
/api/hello
7. Styling in Next.js
a. Global CSS (styles/globals.css)
Import it inside _app.js
:
import "../styles/globals.css";
b. CSS Modules (Component-Level Styling)
import styles from "../styles/Home.module.css"; const Home = () => <h1 className={styles.title}>Styled Title</h1>;
- Scoped styles (no global conflicts).
c. Tailwind CSS (Optional)
Install Tailwind:
npm install -D tailwindcss postcss autoprefixer npx tailwindcss init -p
Configure tailwind.config.js:
module.exports = { content: ["./pages/**/*.{js,ts,jsx,tsx}", "./components/**/*.{js,ts,jsx,tsx}"], theme: { extend: {} }, plugins: [], };
Use Tailwind in components:
<h1 className="text-2xl font-bold text-blue-500">Hello, Tailwind!</h1>
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} />;
Optimized loading and automatic resizing.
9. Environment Variables
Store API keys in .env.local
:
NEXT_PUBLIC_API_URL=https://api.example.com
Access it in Next.js:
const apiUrl = process.env.NEXT_PUBLIC_API_URL;
10. Deploying Next.js
a. Vercel (Recommended)
Vercel is the easiest way to deploy Next.js:
npm install -g vercel vercel
b. Netlify
npm run build
Upload the .next
folder to Netlify.
c. GitHub Pages
- Use Static Export:
next build && next export
- Deploy
/out
folder.