Here’s a quick 20-minute tutorial to get you started with Next.js, a powerful React-based framework for building fast, server-side rendered, and static web applications. This tutorial assumes you already know basic JavaScript and React.
1. What is Next.js? (2 minutes)¶
Next.js is a React framework that enables several key features, including: - Server-side rendering (SSR) and Static site generation (SSG) out of the box. - API routes to create backend functionality directly within your frontend project. - File-based routing for easy URL and navigation management.
2. Setting Up Next.js (3 minutes)¶
You can quickly create a Next.js project using the following steps:
- Install Node.js if you don’t already have it.
- In your terminal, run the following command to create a new Next.js project:
bash npx create-next-app@latest my-next-app - Navigate into your project directory:
bash cd my-next-app - Start the development server:
bash npm run devYour project will now run locally athttp://localhost:3000.
3. Pages and File-based Routing (3 minutes)¶
Next.js uses a file-based routing system. Every file in the pages folder automatically becomes a route in your app.
Creating a new page¶
- Create a new file
about.jsinside thepagesfolder:js // pages/about.js export default function About() { return <h1>About Us</h1>; } - Now visit
http://localhost:3000/aboutto see the new page.
Index Route¶
- The
pages/index.jsfile corresponds to the home page (/).
Dynamic Routing¶
- You can create dynamic routes using square brackets in file names.
For example, create
pages/product/[id].js: ```js // pages/product/[id].js import { useRouter } from 'next/router';
export default function Product() { const router = useRouter(); const { id } = router.query;
return <h1>Product ID: {id}</h1>;
}
``
- Now visithttp://localhost:3000/product/123and it will showProduct ID: 123`.
4. Pre-rendering: SSR vs SSG (4 minutes)¶
Next.js allows you to pre-render pages either on the server (SSR) or at build time (SSG).
Server-side Rendering (SSR)¶
-
Use
getServerSidePropsto fetch data on each request. ```js 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
Static Site Generation (SSG)¶
-
Use
getStaticPropsto generate the page at build time. ```js 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
- You can also use
getStaticPathswith dynamic routes to generate static pages for specific paths: ```js export async function getStaticPaths() { return { paths: [ { params: { id: '1' } }, { params: { id: '2' } }, ], fallback: false, }; }
export async function getStaticProps({ params }) {
const res = await fetch(https://api.example.com/product/${params.id});
const data = await res.json();
return { props: { data } };
} ```
5. API Routes (3 minutes)¶
Next.js allows you to create API routes within your project. API routes are stored in the pages/api folder.
Creating an API Route¶
- Create a file
hello.jsin thepages/apifolder:js // pages/api/hello.js export default function handler(req, res) { res.status(200).json({ message: 'Hello, Next.js!' }); } - Now visit
http://localhost:3000/api/hello, and you’ll get a JSON response{ message: 'Hello, Next.js!' }.
API routes allow you to build backend functionality directly in the Next.js project, such as handling form submissions or working with databases.
6. CSS in Next.js (3 minutes)¶
Next.js supports multiple ways of adding CSS to your project.
Global CSS¶
- In
pages/_app.js, you can import a global CSS file:js import '../styles/globals.css'; function MyApp({ Component, pageProps }) { return <Component {...pageProps} />; } export default MyApp;
CSS Modules¶
- For locally scoped styles, use CSS Modules. Create a CSS file with
.module.cssextension, such asHome.module.css:css /* styles/Home.module.css */ .title { color: red; } - Import and use the CSS module in your component: ```js import styles from './Home.module.css';
export default function Home() { return
Welcome to Next.js
; } ```Styled JSX¶
- Next.js also supports Styled JSX, allowing you to write scoped CSS within your component:
js export default function Home() { return ( <div> <h1>Welcome to Next.js</h1> <style jsx>{` h1 { color: green; } `}</style> </div> ); }
7. API Fetching and Client-side Data Fetching (2 minutes)¶
For client-side data fetching, you can use React hooks like useEffect and useState.
import { useEffect, useState } from 'react';
export default function Page() {
const [data, setData] = useState(null);
useEffect(() => {
async function fetchData() {
const res = await fetch('/api/hello');
const json = await res.json();
setData(json);
}
fetchData();
}, []);
return <div>{data ? data.message : 'Loading...'}</div>;
}
In this example, we fetch data from the local /api/hello route on the client side.
8. Image Optimization (2 minutes)¶
Next.js provides an optimized Image component for handling images, ensuring responsive sizes and automatic optimization.
import Image from 'next/image';
export default function Home() {
return <Image src="/path/to/image.jpg" alt="My Image" width={500} height={300} />;
}
This component optimizes the image for better performance and ensures it is responsive.
9. Deployment (1 minute)¶
Next.js apps are easily deployable on platforms like Vercel. You can push your project to a GitHub repository and deploy it on Vercel with just a few clicks.
- Visit vercel.com and sign in.
- Link your GitHub repository to Vercel and deploy your Next.js app.
Vercel provides automatic optimizations, such as server-side rendering and CDN support.
10. Final Tips (1 minute)¶
- Next.js Documentation: The official Next.js documentation is comprehensive and a great resource for learning more advanced features.
- Focus on SSR and SSG to boost performance and SEO.
- Use the API routes to add backend-like functionality within your Next.js application.
With this basic understanding, you are now ready to start building powerful web applications with Next.js!