Next.js is a powerful React framework that simplifies building fast, scalable web applications. With built-in features like server-side rendering (SSR), static site generation (SSG), and API routes, it provides a great developer experience.
In this quick guide, weβll set up a Next.js project, explore its core features, and build a simple page.
π Prerequisites
β
Node.js installed (recommended: v18+)
β
Basic knowledge of React.js
π Step 1: Setting Up a Next.js Project
To create a new Next.js project, run the following command in your terminal:
npx create-next-app@latest my-next-app
cd my-next-app
npm run dev
This starts a development server at http://localhost:3000.
π
π Step 2: Understanding the Project Structure
A new Next.js project includes:
π pages/ β Each file here becomes a route (e.g., index.js β /)
π public/ β Stores static assets (images, icons, etc.)
π styles/ β Contains global styles and CSS modules
π οΈ Step 3: Creating a Page
Each file inside the pages/ directory automatically becomes a route. Letβs create an About page:
// pages/about.js
export default function About() {
return <h1>About Page</h1>;
}
Visit http://localhost:3000/about
to see it in action!
π¨ Step 4: Styling in Next.js.
Next.js supports global CSS, CSS Modules, and Tailwind CSS.
Using CSS Modules:
Create a CSS file inside the styles/
directory:
/* styles/Home.module.css */
.title {
color: blue;
font-size: 24px;
}
Import it inside a page:
import styles from '../styles/Home.module.css';
export default function Home() {
return <h1 className={styles.title}>Hello Next.js</h1>;
}
π Step 5: Fetching Data in Next.js
Next.js provides multiple ways to fetch data:
- getStaticProps (SSG) β Fetches data at build time
- getServerSideProps (SSR) β Fetches data on every request
- useEffect (CSR) β Fetches data on the client side
- Example using getStaticProps:
export async function getStaticProps() {
const res = await fetch('https://jsonplaceholder.typicode.com/posts');
const posts = await res.json();
return {
props: { posts },
};
}
This method pre-renders the page with fetched data.
π Step 6: Deploying Next.js
You can deploy your Next.js app easily using Vercel (the creators of Next.js).
To deploy:
- Push your project to GitHub
- Go to Vercel and import your repo
- Click Deploy π
π― Final Thoughts
Next.js is an excellent choice for modern web development, offering SEO benefits, fast performance, and easy routing. Start building your first project today!
π Whatβs next? Explore:
πΉ API Routes in Next.js
πΉ Middleware & Authentication
πΉ Server Actions & Optimizations.
Happy coding! π»β¨
Top comments (0)