Next.js

2023-02-08

I have been using Create React App for most of my React projects, but recently I started working with Next.js and it offers quite a lot out of the box. Next.js is a React framework that adds features like server-side rendering, file-based routing, and API routes without needing to set up everything manually.

File-Based Routing

In Create React App, we need to install a routing library like React Router and define routes manually. In Next.js, routing is based on the file structure inside the pages folder. If we create a file called about.js inside pages, it automatically becomes accessible at /about. For dynamic routes, we use square brackets. A file named [id].js inside pages/users will match /users/1, /users/2, and so on.

This makes the routing setup simpler because we do not need to maintain a separate route configuration. The file structure is the route structure.

Rendering Methods

Next.js supports multiple rendering methods, and we can choose different methods for different pages in the same application.

Static Site Generation (SSG) generates the HTML at build time. The page is built once and served as a static file. This is the fastest option because there is no server processing on each request. We use getStaticProps to fetch data at build time.

Server-Side Rendering (SSR) generates the HTML on every request. This is useful for pages that need fresh data on every visit. We use getServerSideProps to fetch data on each request.

Client-Side Rendering works like a regular React app where data is fetched in the browser after the page loads. We can still do this in Next.js using useEffect or data fetching libraries.

API Routes

Next.js also lets us create API endpoints inside the pages/api folder. A file called pages/api/users.js becomes an endpoint at /api/users. This is useful for small backends or for handling things like form submissions without setting up a separate server.

export default function handler(req, res) {
  if (req.method === "GET") {
    res.status(200).json({ users: [] });
  }
}

When to Choose Next.js

If the project needs good SEO, server-side rendering, or a mix of static and dynamic pages, Next.js is a solid choice. For a simple single-page application that does not need SEO or server-side rendering, Create React App or Vite might be simpler to work with. But for most of my new projects, I have been reaching for Next.js because the built-in features save a lot of setup time.