Next js

Introduction to Next.js

Introduction to Next.js


What is Next.js?

  • Next.js is a React framework for building server-rendered and static web applications.

  • It simplifies building React apps with built-in routing, server-side rendering (SSR), static site generation (SSG), and API routes.

  • Created by Vercel and widely used for production React apps.


Why Use Next.js?

  • Automatic routing based on the pages directory.

  • Supports Server-Side Rendering (SSR) and Static Site Generation (SSG).

  • Built-in CSS and Sass support.

  • API routes for backend functionality inside the same app.

  • Optimized for performance, SEO-friendly.

  • Easy deployment with Vercel or other platforms.


Basic Next.js App Structure

java
my-next-app/
├── pages/
│ ├── index.js // Home page
│ └── about.js // About page
├── public/ // Static assets like images
├── styles/ // CSS styles
├── package.json

Creating Pages

Each file in the pages/ folder automatically becomes a route.

pages/index.js

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

pages/about.js

jsx
export default function About() {
return <h1>About Us</h1>;
}

Visiting / shows Home page, /about shows About page.


Server-Side Rendering (SSR)

Next.js lets you fetch data on the server at request time using getServerSideProps.

jsx
export async function getServerSideProps() {
// fetch data here
return { props: { message: "Hello from SSR!" } };
}

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


Static Site Generation (SSG)

Generate pages at build time using getStaticProps.

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

Define backend endpoints inside pages/api.

pages/api/hello.js

js
export default function handler(req, res) {
res.status(200).json({ text: "Hello from API" });
}

Running a 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

Feature Description
File-based Routing Pages auto-routed based on pages folder
SSR & SSG Render pages on server or at build time
API Routes Serverless backend functions inside app
Built-in CSS Support Supports CSS, Sass, and CSS modules
Easy Deployment Optimized for deployment on Vercel and others

Leave a Reply

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