A Next.js project is a React-based framework that offers server-side rendering, static site generation, and more features for building modern web applications. Here’s a quick overview of how to get started with a Next.js project:
Create a New Next.js Application:
Use npx
to create a new Next.js project:
npx create-next-app@latest my-nextjs-app
Replace my-nextjs-app
with your desired project name.
Navigate to the Project Directory:
cd my-nextjs-app
Install Dependencies: Next.js will automatically install the necessary dependencies when you create the project. However, you can add more dependencies as needed using npm or yarn:
npm install # or yarn install
pages/
: Contains your application's routes. Each file inside this directory maps to a route based on its file name.
index.js
: The default route (/
).[...params].js
: Dynamic routing.public/
: Static assets such as images and fonts.
styles/
: Contains global styles and CSS modules.
next.config.js
: Configuration file for customizing Next.js settings.
package.json
: Manages project dependencies and scripts.
Create a New Page:
Add a new file to the pages/
directory, for example, about.js
:
// pages/about.js export default function About() { return <h1>About Us</h1>; }
Create Components:
Create reusable components in the components/
directory:
// components/Navbar.js export default function Navbar() { return ( <nav> <a href="/">Home</a> <a href="/about">About</a> </nav> ); }
Server-side Rendering (SSR): Fetch data on each request:
// pages/posts.js export async function getServerSideProps() { const res = await fetch('https://api.example.com/posts'); const posts = await res.json(); return { props: { posts } }; } export default function Posts({ posts }) { return ( <div> {posts.map(post => ( <h2 key={post.id}>{post.title}</h2> ))} </div> ); }
Static Site Generation (SSG): Fetch data at build time:
// pages/posts.js export async function getStaticProps() { const res = await fetch('https://api.example.com/posts'); const posts = await res.json(); return { props: { posts } }; } export default function Posts({ posts }) { return ( <div> {posts.map(post => ( <h2 key={post.id}>{post.title}</h2> ))} </div> ); }
Start the development server to see your changes:
npm run dev # or yarn dev
Visit http://localhost:3000
in your browser to see your app.
Build the Application:
npm run build # or yarn build
Start the Production Server:
npm start # or yarn start
Deploy: You can deploy Next.js apps to platforms like Vercel, Netlify, or your preferred hosting provider. Vercel is the company behind Next.js and offers a seamless deployment experience.