Next.js is a React framework that provides several key features for building production-grade applications, such as server-side rendering, static site generation, and API routes. If you are familiar with React, transitioning to Next.js will enhance your productivity and simplify your development process.
Key Differences Between React and NextJS
Feature | ReactJS | NextJS |
---|---|---|
Routing | Uses react-router | File-based routing (no need for react-router ) |
Data Fetching | Uses useEffect or third-party libraries (e.g., SWR, Axios) | Server-Side Rendering (SSR) and Static Site Generation (SSG) via getServerSideProps and getStaticProps |
API Routes | Typically needs Express or other backend | Built-in API routes using /pages/api |
Rendering | Client-side rendering (CSR) | SSR, SSG, and ISR (Incremental Static Regeneration) |
SEO Optimization | Manual SEO handling | Built-in SEO optimization, head management |
File Structure | Freeform, customizable | Conventional folder structure (pages , public , etc.) |
Development Mode | Create React App (npm start ) | Fast refresh with next dev |
Deployment | Needs configuration for SSR/SSG | Easily deployable on platforms like Vercel |
Setting Up a NextJS Project
-
Install Next.js with
npx
oryarn
:npx create-next-app@latest my-next-app
# OR
yarn create next-app my-next-app -
Start the development server:
cd my-next-app
npm run dev -
Folder Structure Overview:
pages/
- Contains all the routes for your application.pages/api/
- Holds API route handlers.public/
- Serves static files (images, fonts, etc.).styles/
- Contains your CSS/SCSS files.
Routing in NextJS
ReactJS:
In React, you use react-router for defining routes.
// App.js in React
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
function App() {
return (
<Router>
<Switch>
<Route path="/about" component={About} />
<Route path="/contact" component={Contact} />
</Switch>
</Router>
);
}
NextJS:
Next.js uses a file-based routing system. The files you place in the pages/
directory automatically become routes.
// pages/index.js (Home Page)
export default function Home() {
return <h1>Home Page</h1>;
}
// pages/about.js (About Page)
export default function About() {
return <h1>About Page</h1>;
}
To create dynamic routes:
// pages/posts/[id].js (Dynamic Route)
import { useRouter } from 'next/router';
export default function Post() {
const router = useRouter();
const { id } = router.query;
return <h1>Post ID: {id}</h1>;
}
Fetching Data in NextJS
Next.js offers multiple ways to fetch data:
Client-Side Fetching (Same as React):
You can still use useEffect and libraries like fetch
or axios
.
import { useEffect, useState } from 'react';
export default function Page() {
const [data, setData] = useState(null);
useEffect(() => {
fetch('/api/data')
.then((response) => response.json())
.then((data) => setData(data));
}, []);
return <div>{JSON.stringify(data)}</div>;
}
Server-Side Fetching:
- getServerSideProps: Fetch data on each request (SSR).
export async function getServerSideProps() {
const res = await fetch('https://api.example.com/data');
const data = await res.json();
return { props: { data } };
}
export default function Page({ data }) {
return <div>{JSON.stringify(data)}</div>;
}
- getStaticProps: Fetch data at build time (SSG).
export async function getStaticProps() {
const res = await fetch('https://api.example.com/data');
const data = await res.json();
return { props: { data } };
}
export default function Page({ data }) {
return <div>{JSON.stringify(data)}</div>;
}
API Routes in NextJS
Next.js allows you to create API routes within your application without setting up an external server.
- Create an API route by adding a file to the pages/api/ folder.
// pages/api/hello.js
export default function handler(req, res) {
res.status(200).json({ message: 'Hello, Next.js API!' });
}
Access the API at http://localhost:3000/api/hello.
Styling in NextJS
You can use any CSS method you prefer: CSS Modules, SCSS, TailwindCSS, or plain CSS.
-
CSS Modules:
- Create a CSS file with .module.css extension and import it directly into your component.
// styles/Home.module.css
.container {
background-color: lightblue;
}import styles from '../styles/Home.module.css';
export default function Home() {
return <div className={styles.container}>Welcome!</div>;
} -
Global Styles:
- Define global styles in
styles/globals.css
and import in_app.js
.
- Define global styles in
Deployment
-
Vercel (Recommended): Next.js was created by Vercel, so deployment is extremely easy.
- Connect your GitHub/GitLab repository to Vercel.
- Each push to main triggers a new deployment.
-
Custom Deployment:
- For traditional servers, run the following build commands:
npm run build
npm run start- Deploy the .next folder and server.js on any server that supports Node.js.
-
Static Exports:
- If your site is entirely static, you can export it using:
npm run export
Development Best Practices
-
Use Pre-rendering: Take advantage of static generation (
getStaticProps
) and server-side rendering (getServerSideProps
) to optimize your pages. -
API Routes: Leverage built-in API routes for quick API development without the need for external servers.
-
SEO Optimization: Use the built-in
<Head>
component for managing metadata, page titles, and descriptions. -
Environment Variables: Store sensitive information in
.env.local
and access them via process.env.// Example usage in Next.js
const apiKey = process.env.NEXT_PUBLIC_API_KEY; -
Optimization: Use Next.js's next/image component to optimize image loading and responsiveness.
import Image from 'next/image';
<Image src="/example.jpg" width={500} height={300} alt="Example Image" />; -
Fast Refresh: Next.js provides fast refresh in development, giving an instant feedback loop.
-
Custom Error Pages: Create custom 404 or error pages by adding
404.js
or_error.js
in thepages/
folder.
By following this guide, you’ll be able to transition from ReactJS to NextJS smoothly and leverage the additional features NextJS provides for building scalable and performant applications.
Explanation of Sections:
- Key Differences: Provides a table to give an overview of how NextJS differs from ReactJS.
- Routing: Describes how routing is simplified in NextJS without the need for third-party libraries.
- Data Fetching: Explains the three main ways to fetch data (client-side, server-side, and static).
- API Routes: Introduces the built-in API routing system in NextJS.
- Styling: Covers CSS Modules and Global styles in NextJS.
- Deployment: Shows how to deploy to Vercel or other servers.
- Best Practices: Highlights important features to make development in NextJS easier.