Introduction
Earlier this year, ReactJS’ official documentation recommended using the NextJS framework for React full-stack applications. As a ReactJS developer, learning Nextjs could be beneficial.
On May 4th, 2023, NextJS, in its blog post, announced the release of a stable NextJS version 13.4, marking stability for the App Router.
In this article, I will highlight some of the essential features NextJS introduced.
Prerequisites
Before we get started, be sure to have the following:
- Node.js 16.8 or later installed.
- Operating system (MacOS, Windows, or Linux)
Overview
Below are some of the Next.js 13 features we will be looking at:
- File & Folder Structure
- Server & Client side component
- Routing & Special Next.js Files
- Data fetching (SSR, SSG, ISR)
- Next.js API Endpoints
- SEO & Metadata
File & Folder Structure in Next 13.
To explain the concept file & folder structure in Next 13, let's create a new NextJS project.
Creating a NextJS application
To bootstrap a NextJS project, run the command below in the terminal and follow the prompts below to keep things simple and consistent.
npx create-next-app@latest
Once installation is completed, we should have our application file and folder as below:
Below are some of the most important files/folders
- The
app
folder is the most important in a Next.js app and contains thefavicon.ico
,globals.css
,layout.js
,page.js
, andpage.module.css
files, which are the most important files for now. - The
layout.js
file is the application's main entry point, and all the components are wrapped within it as children. This file allows us to personalize the behavior of our application by providing a common layout or template for all pages. Components included in this file will be shared throughout the entire application. In our application, if we want to add something consistent across all routes, such as a navbar, footer, or Redux Toolkit wrapper, we should place it in thelayout.js
file. - The
page.js
file represents the home page route of the application. - The
page.module.css
file represents the corresponding CSS file forpage.js
. - The
globals.css
file contains the global CSS styles of the entire application. It is imported within the layout file so that every route inherits it.
Some other file conventions that are introduced are error.js
, loading.js,
etc. We could read more on file and folder structure.
Server & Client-side Component
React 18 and Next 13 have introduced new methods for component rendering, enabling components to be rendered on the server or client sides. In NextJS, all components developed within the app folder are server-side by default. This approach improves initial page load times, enhancing SEO and user experience. If there is a need to convert a server-side component to a client-side one, all we need to do is add the "use client" directive at the top of the page. For example
// by default pages are server-side,
// adding `use client` turns the page to client-side page
'use client'
import React from 'react'
const page = () => {
return (
<div>
client-side-page
</div>
)
}
export default page
Why would we want to turn our component to client-side? Generally, NextJS recommends using server components. However, we have to use client-side components when we have interactivity or event listeners, like onClick
, onChange
, or when using react hooks. We can also use client-side components when using custom hooks that depend on state, effects, or browser-only APIs.
NextJS provides a helpful table on when to use server components and when to use client components, check it out.
Routing in NextJS
In NextJS 13 routing system, all we need to do to implement the routing in NextJS is create a folder corresponding to the desired route within the app
folder; the folder's name will serve as the route name.
Routes in NextJS 13
To create a route, create a folder corresponding to the desired route within the app
folder; the folder's name will serve as the route path. For instance, let's say we want to create a /user
route.
- Navigate to the
app folder
- Create a new folder called
user
- Then within the
user
folder, create a newpage.js
file within which we can create a react functional component.
The file directory should be as /app/user/page.js
This page can be accessed at localhost:3000/user
.
Nested Route in NextJS 13
We could create a nested route simply by following the same convention. To create a nested route such as localhost:3000/user/customer
, create a customer
folder within the user
folder and create a page.js
file as shown below. The file directory should be as /app/user/customer/page.js
Dynamic Route in NextJS 13
Similar to creating a route, but this time, the folder name will be wrapped with a squared bracket []
, where the folder name represents the dynamic value. For instance, let's say we want to create a page that fetches customer by customer_id
and routes as /user/customer/1
such that the value could be any customer_id e.g /user/customer/1
, /user/customer/2
etc.
Simply create a [customer_id]
folder within the customer
folder and create a page.js
file as shown below. The file directory should be as /app/user/customer/[customer_id]/page.js
To access the customer_id
within the page, we could destructure from its params
as shown above.
NextJS Data Fetching (SSR, SSG, ISR)
NextJS introduces three choices for selecting how to fetch data. Let's explore all of these one by one first we have.
NextJS Server Side Rendering (SSR)
Server-side rendering refers to dynamically rendering data on the server side. This means that new data is retrieved for each request. With SSR, every request to the server initiates a new rendering cycle and data retrieval, guaranteeing that the content is consistently updated.
In NextJS, we need to include an object { cache: "no-store" }
in the fetch request to implement SSR. See the example shown below.
import React from "react";
const SSR = async () => {
//1. Server-side rendering (SSR)
const res = await fetch(
`https://jsonplaceholder.typicode.com/post/1`,
{ cache: "no-store" } //this makes it SSR
);
const data = res.json();
return <div>SSR</div>;
};
export default SSR;
The above will make sure the request is always consistent and never cached.
NextJS Static Side Generation (SSG)
By default, NextJs fetches data using the static site generation, which automatically fetches the specified data. It also caches the data.
The only necessary step when using static site generation is not adding { cache: "no-store" }
in the fetch request. This approach is well-suited for content that doesn't undergo frequent changes, such as blog posts, documentation, or marketing pages. See the example shown below.
import React from 'react'
const SSG = async () => {
//2. Static side generation (SSG)
const res = await fetch(
`https://jsonplaceholder.typicode.com/post/1`
)
//remove the cache : 'no-store' makes it SSG
const data = res.json()
return (
<div>
SSG
</div>
)
}
export default SSG
NextJS Incremental Static Regeneration (ISR)
Incremental Static Regeneration combines the benefits of SSR and SSG for dynamic content in static sites; with the incremental static generation, we can fetch at build time while defining a revalidation time interval; this means that the data will be cached, but after a specific time frame it's then going to refresh it.
In ISR, instead of messing with the cache, we can provide an additional parameter here { next: { revalidate: 10 } }
, it is in seconds. See the example shown below.
import React from "react";
const ISR = async () => {
//3. Incremental static regeneration (ISR)
const res = await fetch(
`https://jsonplaceholder.typicode.com/post/1`,
{ next: { revalidate: 10 } } //refetch after 10 seconds
);
const data = res.json();
return <div>ISR</div>;
};
export default ISR;
Next.js API Endpoints (Route Handlers)
Next.js enables full-stack applications, allowing operation on both the front-end and back-end. It accomplishes this by utilizing a file-based routing system. With Next.js, developers can handle HTTP requests and build back-end functionality without needing an external server.
Route Handlers allow the creation of custom request handlers for a given route using the Web Request and Response APIs.
To create an API endpoint in NextJS, we need to create a folder corresponding to the desired endpoint within the app
folder; the folder's name will serve as the endpoint.
However, creating API endpoints within an api
folder in the app
folder is advisable to differentiate between pages and APIs.
For instance, let's say we want to create an api/user
endpoint. Follow the steps below.
- Navigate to the
app
folder - Create a new folder called
api
- Within the
api
folder, create a new folder calleduser
- Next, within the
user
folder, create a newroute.js
file within which we can create a react functional component.
The file directory should be as /app/api/user/route.js
.
Therefore this endpoint would be api/user
. See folder structure below.
SEO & Metadata
Metadata refers to the information embedded in a web page that provides descriptive details about the page content. It plays a crucial role in search engine optimization (SEO) by helping search engines accurately understand and index the page.
Next.js introduces an additional metadata API that offers two approaches for handling metadata: static-generated and dynamically-generated metadata. These options provide enhanced flexibility in managing metadata within Next.js.
Static Metadata
Static metadata refers to the information that can be defined statically and is associated with a particular page or component.
To make changes to the metadata in a static manner. We export a specific object called metadata
that holds the desired metadata, as demonstrated below.
import React from 'react'
//static metadata here
export const metadata = {
title : 'product title',
descriptions : 'page description goes here'
}
export const page = () => {
return (
<div>page</div>
)
}
Dynamically Generated Metadata
Imagine a page that renders product information; majorly, such a page will be a dynamic page such that the product will be fetched by a key (usually ID); in this type of scenario, it is best to use dynamically generated metadata.
By utilizing dynamically generated metadata in Next.js, we can provide tailored information for each page based on its content or context. This enables search engines, social media platforms, and other tools to understand better and present our pages, ultimately improving our website's visibility and user experience.
To modify the metadata dynamically, we will export a special function called generateMetadata
as shown below.
import React from 'react'
const getProduct = ()=>{
//get product here
}
// call the generateMetadata function
export async function generateMetadata({params}) {
const product = await getProduct(params.id);
return{
title : product.title
}
}
export const page = () => {
return (
<div>page</div>
)
}
Conclusion
NextJS, in its blog post, announces the release of a stable NextJS version 13.4. In this article, I highlighted some important features Next.js 13 introduced.
If this article is helpful, consider liking, sharing, and following me; connect with me on Twitter for more exciting articles like this.
Happy coding.
Top comments (0)