Horje
Route Segment Config Next.js

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
app

choose the option as shown using right left arrow and press enter.

Folder Structure

FolderStrucutre

Folder Strucutre

Updated 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

outputtt

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.



Reffered: https://www.geeksforgeeks.org


ReactJS

Related
Marko vs React Marko vs React
How does Concurrent Mode Help in Improving The User Experience? How does Concurrent Mode Help in Improving The User Experience?
What are Some Common Libraries/Tools for Form Handling in Redux? What are Some Common Libraries/Tools for Form Handling in Redux?
How to Disable Server Side Rendering on Some Pages in Next.js ? How to Disable Server Side Rendering on Some Pages in Next.js ?
Why Do We Need Middleware for Async Flow in Redux? Why Do We Need Middleware for Async Flow in Redux?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
17