From Zero to Junior in One Day: Your First Day with Next.js
Welcome to the world of Next.js! If you’re a developer stepping into Next.js for the first time, this guide will walk you through the essential concepts and features you’ll need to understand to get up and running quickly. By the end of this article, you’ll have a solid foundation to build and deploy your own Next.js applications.
What is Next.js?
Next.js is a React framework that enables you to build server-side rendering (SSR) and static web applications. It combines the best features of React, the most popular front-end library, with powerful features like automatic static optimization, dynamic routing, and more. Here’s a rundown of what makes Next.js special:
- Server-Side Rendering (SSR): Automatically renders pages on the server to improve SEO and performance.
- Static Site Generation (SSG): Pre-renders pages at build time, ensuring fast load times and a great user experience.
- API Routes: Create API endpoints within your Next.js application without needing an external server.
- File-based Routing: Simplifies navigation by using the filesystem for routing.
- Automatic Code Splitting: Ensures that each page only loads what’s necessary, improving performance.
Getting Started with Next.js
Installation
First, you need to have Node.js and npm (or yarn) installed. You can create a new Next.js project using the following command:
npx create-next-app my-next-app
cd my-next-app
npm run dev
This will set up a new Next.js project and start a development server at http://localhost:3000
.
Project Structure
A basic Next.js project structure looks like this:
my-next-app/
├── pages/
│ ├── api/
│ │ └── hello.js
│ ├── _app.js
│ ├── _document.js
│ └── index.js
├── public/
├── styles/
│ ├── globals.css
│ └── Home.module.css
├── package.json
└── next.config.js
- pages/: This directory is used for routing. Each file in this directory becomes a route.
- api/: Contains API routes.
- _app.js: Customizes the default App component.
- _document.js: Customizes the default Document component.
- index.js: The main page of the application.
- public/: Static assets like images and fonts.
- styles/: CSS modules and global styles.
Core Concepts
Pages and Routing
In Next.js, each file in the pages
directory automatically becomes a route. For example, pages/index.js
maps to the root URL /
, and pages/about.js
maps to /about
.
// pages/index.js
export default function Home() {
return <h1>Welcome to Next.js!</h1>;
}
Server-Side Rendering (SSR) and Static Generation
Next.js supports different rendering methods:
- Static Generation (SSG): Pre-renders pages at build time.
- Server-Side Rendering (SSR): Pre-renders pages on each request.
You can choose the rendering method using getStaticProps
and getServerSideProps
.
// pages/index.js
// This function runs at build time
export async function getStaticProps() {
return {
props: {
message: "Hello, world!",
},
};
}
export default function Home({ message }) {
return <h1>{message}</h1>;
}
API Routes
Next.js allows you to create API endpoints directly within the pages/api
directory.
// pages/api/hello.js
export default function handler(req, res) {
res.status(200).json({ message: "Hello from Next.js!" });
}
Dynamic Routing
Dynamic routes can be created using brackets in the file name.
// pages/posts/[id].js
import { useRouter } from "next/router";
export default function Post() {
const router = useRouter();
const { id } = router.query;
return <h1>Post ID: {id}</h1>;
}
React Basics Refresher
Components and Props
In React (and hence Next.js), components are the building blocks of the UI. Props are used to pass data from parent to child components.
// components/Greeting.js
export default function Greeting({ name }) {
return <h1>Hello, {name}!</h1>;
}
// pages/index.js
import Greeting from '../components/Greeting';
export default function Home() {
return <Greeting name="Next.js Developer" />;
}
State and Lifecycle
React components can have state, which is managed using the useState
hook, and lifecycle methods managed with the useEffect
hook.
import { useState, useEffect } from "react";
export default function Counter() {
const [count, setCount] = useState(0);
useEffect(() => {
console.log(`Count is: ${count}`);
}, [count]);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
Styling in Next.js
Next.js supports various ways to style your application:
- CSS Modules: Scoped styles.
- Global CSS: Global styles applied to the whole application.
- Styled JSX: Scoped CSS-in-JS.
CSS Modules
// styles/Home.module.css
.container {
padding: 20px;
text-align: center;
}
// pages/index.js
import styles from '../styles/Home.module.css';
export default function Home() {
return <div className={styles.container}>Hello, Next.js!</div>;
}
Global CSS
/* styles/globals.css */
body {
font-family: Arial, sans-serif;
}
// pages/_app.js
import "../styles/globals.css";
export default function App({ Component, pageProps }) {
return <Component {...pageProps} />;
}
Deployment
Next.js applications can be deployed on various platforms, including Vercel (the creators of Next.js), Netlify, and more. Deploying to Vercel is straightforward:
- Push your code to GitHub.
- Sign up on Vercel and import your repository.
- Vercel will automatically build and deploy your application.
Conclusion
By now, you should have a good grasp of the fundamental concepts of Next.js. From setting up a project to understanding routing, SSR, SSG, API routes, and basic React concepts, you’re well on your way to building powerful web applications with Next.js.
Code with passion, create with purpose!