Next.js
Next.js is a popular React framework for building server-rendered and statically generated web applications. It provides a streamlined development experience by offering built-in routing, server-side rendering, and static site generation capabilities. Next.js combines the power of React with server-side rendering, allowing developers to create fast and SEO-friendly web applications. It offers features like code splitting, automatic routing, and built-in API routes for creating robust and scalable applications.
Module 1: Getting Started with Next.js
Introduction to Next.js
Next.js is a React framework that provides infrastructure and simple development experience for server-rendered React applications.
Setting Up a Next.js Project
Learn how to setup a new Next.js project using create-next-app, which sets up everything automatically for you.
npx create-next-app@latest nextjs-app
Pages in Next.js
In Next.js, a page is a React Component exported from a .js, .jsx, .ts, or .tsx file in the pages directory. Each page is associated with a route based on its file name.
export default function Home() { return <div>Welcome to Next.js!</div> }
Module 2: Routing and Linking in Next.js
Next.js Routing
Next.js has a file-system based router built on the concept of pages. When a file is added to the pages directory it's automatically available as a route.
pages/index.js -> '/' pages/posts.js -> '/posts'
Link Component
The Next.js Link component enables client-side navigation between different pages in your application.
import Link from 'next/link' export default function Navigation() { return ( <Link href='/posts'> <a>Posts</a> </Link> ) }
Dynamic Routes
Next.js supports dynamic routes, and the pages directory can have dynamic segments.
pages/posts/[id].js -> '/posts/1', '/posts/2', '/posts/n'
Module 3: Data Fetching in Next.js
getStaticProps
getStaticProps allows you to fetch data at build time and pre-render the page with the fetched data.
export async function getStaticProps() { const res = await fetch('https://.../posts') const posts = await res.json() return { props: { posts, }, } }
getServerSideProps
If you need to fetch data at request time instead of at build time, you can use getServerSideProps.
export async function getServerSideProps(context) { const res = await fetch(`https://.../posts/${context.params.id}`) const post = await res.json() return { props: { post, }, } }
getStaticPaths
getStaticPaths is used for dynamic routes to define a list of paths that have to be rendered to HTML at build time.
export async function getStaticPaths() { return { paths: [ { params: { id: '1' } }, { params: { id: '2' } } ], fallback: false } }