Route Segment Config Next.js
Last Updated :
04 Jul, 2024
Next.js, a popular React framework, continues to evolve, adding features that enhance web application efficiency and scalability. One such feature is Route Segment Config, providing control over route handling and configuration.
What is Route Segment Config?
Route Segment Config allows developers to define configuration options for specific route segments. It's useful for setting up middleware, custom layouts, and data fetching strategies per segment. This results in better-organized and more maintainable code.
Route Segment Config Options in Next.js:
Option | Type | Default | Description |
---|
dynamic | auto | force-dynamic | error | force-static | auto | Sets if a route is statically or dynamically rendered. |
---|
dynamicParams | boolean | true | Includes dynamic route parameters. |
---|
revalidate | false | 0 | number | false | Revalidation period for Incremental Static Regeneration (ISR). |
---|
fetchCache | auto | default-cache | only-cache | force-cache | force-no-store | default-no-store | only-no-store | auto | Caching strategy for data fetching. |
---|
runtime | nodejs | edge | nodejs | specify the runtime environment |
---|
preferredRegion | auto | global | home | string | string[] | auto | Preferred region for code execution. |
---|
maxDuration | number | set by development platform | Maximum duration for server-side rendering operations. |
---|
Next.js provides various configuration options for route segments to help developers control routing behaviour, below is the overview of these options:
- generateStaticParams: Defines dynamic routes and their static parameters for static site generation.
- revalidate: Configures the revalidation period for incremental static regeneration, specifying how often the page should be regenerated.
- dynamic: Determines the type of dynamic fetching strategy, such as "force-static", "force-dynamic", "blocking", or "unstable-cache".
- fetchCache : Specifies caching behavior for data fetching, improving performance by caching fetched data.
- runtime: Sets the runtime environment, like "edge" or "nodejs", for server-side operations.
Steps To Implement Route Segment Config
To implement Route Segment Config in Next.js, follow these steps:
Step1: Create next.js project using the following commands:
npx create-next-app demosegmentation
choose the option as shown using right left arrow and press enter.Folder Structure
Folder StrucutreUpdated Dependencies
"dependencies":
{
"react": "^18",
"react-dom": "^18",
"next": "14.2.3"
}
Step 2: Navigate to project folder with following command or open with file->open folder option in vscode.
cd demosegmentation
Step 3: Creating route segments in pages directory as shown in above project structure.
- Create a "dummyData.js" file in the api directory.
- Create a "_segmentConfig.js" file in pages directory.
Step 4: Create a Dummy API
Create an API route that returns some dummy data. This is done by adding an API route in the pages/api directory.
Step 5: Create Route Segment Config for the Home Page
Create a "_segmentConfig.js" file in the pages directory to define the configuration for the home page.
Step 6: Apply the Configurations in the Home Page
Update the pages/index.js file to import and use the segment configuration.
Example: To demonstrate creating route segment congif using Next.js
JavaScript
// src/pages/api/dummyData.js
export default function handler(req, res) {
res.status(200).json({
message: "Welcome to our website!",
features: [
{
id: 1,
title: "Fast Performance",
description: "Our site is blazing fast.",
},
{
id: 2,
title: "High Security",
description: "Your data is safe with us.",
},
{
id: 3,
title: "Responsive Design",
description: "Looks great on any device.",
},
],
});
}
JavaScript
// src/pages/_segmentConfig.js
export default {
layout: "homeLayout",
fetchData: async () => {
const res = await fetch("http://localhost:3000/api/dummyData");
if (!res.ok) {
throw new Error(`Failed to fetch data: ${res.statusText}`);
}
const data = await res.json();
return { data };
},
};
JavaScript
// src/pages/index.js
import segmentConfig from "./_segmentConfig";
const Home = ({ data }) => {
return (
<div>
<h1>{data.message}</h1>
<ul>
{data.features.map((feature) => (
<li key={feature.id}>
<h2>{feature.title}</h2>
<p>{feature.description}</p>
</li>
))}
</ul>
</div>
);
};
export async function getServerSideProps() {
try {
const config = await segmentConfig.fetchData();
return {
props: {
...config,
},
};
} catch (error) {
console.error(error);
return {
notFound: true,
};
}
}
export default Home;
Step 7: Run the Next.js development server to see the changes in action:
npm run dev
visit http://localhost:3000 in browser to verify output.
Output
Route Segment Config Next.js Benefits of Route Segment Config
- Granular Control: Apply configurations to specific segments.
- Modularity: Break down route configurations into reusable segments.
- Improved Performance: Optimize by applying essential configurations only where needed.
- Better Code Organization: Enhance readability and maintainability by separating concerns.
Similar Reads
Next.js Dynamic Route Segments Dynamic routing is a core feature in modern web frameworks, enabling applications to handle variable paths based on user input or dynamic content. In Next.js 13+, with the introduction of the App Router, dynamic routes are implemented using a folder-based structure inside the app directory.This arti
2 min read
Next.js Injecting the router In this article, we will learn how we can inject the router into our NextJS project. NextJS is a React-based framework. It has the power to Develop beautiful Web applications for different platforms like Windows, Linux, and mac. Next.js has a file-system-based router built on the concept of pages. W
3 min read
Next.js Intercepting Routes Next.js is the most widely used React framework. With each new major release, the Next.js team is adding amazing features to the framework. Here, We will deep dive into a feature called Intercepting Routes which was added in a recent release to render modal on the same page with a unique URL. Interc
7 min read
How to use Next.js API Routes? Next.js API Routes are a feature of Next.js that allows you to create server-side logic and APIs within your Next.js application. These API routes are implemented using files in the `pages/api` directory of your Next.js project. When you deploy your Next.js application, these API routes are automati
8 min read
Next.js Functions: useSelectedLayoutSegment Next.js framework has various useful functions that are used to enhance navigation and routing within applications. One such function is useSelectedLayoutSegment, a client-side hook that allows developers to access the active route segment one level below the current Layout. This function is particu
3 min read