Next js

Next.js Fundamentals

What is Next.js?

  • A React framework for building server-rendered and static web apps.

  • Offers file-based routing, automatic code splitting, SSR (Server-Side Rendering), and SSG (Static Site Generation).

  • Simplifies building performant, SEO-friendly React apps.


Core Features

Feature Description
File-based Routing Pages created by adding files to the pages/ directory; filenames map to URLs
Server-Side Rendering (SSR) Render pages on the server per request (getServerSideProps)
Static Site Generation (SSG) Pre-render pages at build time (getStaticProps)
API Routes Backend endpoints inside pages/api/
Built-in CSS Support Supports CSS, Sass, CSS Modules out of the box
Image Optimization Next/Image component optimizes images automatically
Fast Refresh Instant feedback during development

Project Structure

arduino
my-next-app/
├── pages/
│ ├── index.js // Home page route '/'
│ ├── about.js // '/about'
│ └── api/
│ └── hello.js // API route '/api/hello'
├── public/ // Static assets (images, favicon)
├── styles/ // CSS files or modules
├── next.config.js // Optional configuration

Basic Page Example

jsx
// pages/index.js
export default function Home() {
return <h1>Welcome to Next.js!</h1>;
}

Data Fetching Methods

Method When to use Example use case
getStaticProps Fetch data at build time (SSG) Blog posts, documentation
getServerSideProps Fetch data on every request (SSR) User-specific data, dashboards
getStaticPaths Define dynamic routes to pre-render at build Dynamic blog posts, products

Example: Static Generation

jsx
export async function getStaticProps() {
// Fetch data here
return {
props: {
message: 'Hello from SSG!'
}
};
}

export default function Page({ message }) {
return <div>{message}</div>;
}


API Routes Example

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

Running Your Next.js App

bash
npx create-next-app my-next-app
cd my-next-app
npm run dev

Open http://localhost:3000 in your browser.


Summary

  • Next.js enables server-rendered and static React apps.

  • Uses file-based routing — add files in pages/ for routes.

  • Supports API routes to build backend logic inside your app.

  • Flexible data fetching with SSR & SSG.

  • Built-in features like CSS support, image optimization, and fast refresh.

Leave a Reply

Your email address will not be published. Required fields are marked *