How to Build Specific Routes or Pages in Next.js Efficiently"

Published on

Jan 21, 2025

Rishabh Ranjan

7 mins

Developing a Next.js web application often involves optimizing build times and resource usage. In large-scale applications or those with dynamic content, it's important to avoid generating unnecessary pages during the initial build. Next.js provides several mechanisms to selectively build pages, allowing developers to balance performance and flexibility.

Why Build Specific Routes?

  1. Optimized Build Times:
    Building only the necessary pages reduces build time, which is particularly beneficial in continuous integration and deployment (CI/CD) pipelines. It also minimizes downtime during updates.
  2. Dynamic Content Requirements:
    Applications with dynamic content that changes frequently or is user-specific may not benefit from pre-built pages. These pages are better served dynamically at runtime.
  3. Resource Efficiency:
    Pre-building every possible route in large applications can be resource-intensive, both during the build process and in terms of storage. Limiting the scope of pre-built pages ensures a leaner and more efficient setup.

Methods to Build Specific Routes

1. Using getStaticPaths

When leveraging static site generation (SSG), the getStaticPaths function enables you to define which pages should be built at build time. This method is ideal for applications where only a subset of routes is known beforehand, while others can be generated dynamically on request.

export async function getStaticPaths() {
  const paths = [
    { params: { slug: 'page1' } },
    { params: { slug: 'page2' } },
  ];

  return {
    paths, // Only these pages will be pre-built
    fallback: 'blocking', // Other pages will be generated dynamically
  };
}

export async function getStaticProps({ params }) {
  const { slug } = params;

  // Fetch data specific to this slug
  return {
    props: { slug },
  };
}

const Page = ({ slug }) => {
  return <div>{`This is page ${slug}`}</div>;
};

export default Page;
  • Fallback Modes:some text
    • blocking: Generates pages on-demand, serving the complete page to the user after rendering.
    • true: Shows a loading state (fallback UI) until the page is built dynamically.
    • false: Returns a 404 for paths not pre-built.

2. Dynamic Routes with getServerSideProps:

Using getServerSideProps, you can completely avoid pre-building and instead generate pages dynamically at runtime. This method is ideal for pages requiring real-time data or user-specific content.

export async function getServerSideProps({ params }) {
  const { slug } = params;

  // Fetch data for this slug
  return {
    props: { slug },
  };
}

const Page = ({ slug }) => {
  return <div>{`This is page ${slug}`}</div>;
};

export default Page;
  • Advantages:some text
    • Fully dynamic, ensuring up-to-date content.
    • No additional build time for dynamic routes.

3. Incremental Static Regeneration (ISR)

ISR combines the best of SSG and SSR by allowing pages to be pre-built and dynamically updated based on traffic or a specified interval.

export async function getStaticPaths() {
  const paths = [
    { params: { slug: 'page1' } },
    { params: { slug: 'page2' } },
  ];

  return {
    paths,
    fallback: 'blocking',
  };
}

export async function getStaticProps({ params }) {
  const { slug } = params;

  // Fetch data for this slug
  return {
    props: { slug },
    revalidate: 60, // Page will be rebuilt after 60 seconds
  };
}

const Page = ({ slug }) => {
  return <div>{`This is page ${slug}`}</div>;
};

export default Page;
  • Advantages:some text
    • Pre-built pages load faster.
    • Updated data can be fetched periodically, ensuring freshness without rebuilding the entire app.

4. Manual Page Inclusion

For smaller applications, you can include only the required pages by manually creating their files in the pages directory or using dynamic imports.


import dynamic from 'next/dynamic';

const Page1 = dynamic(() => import('./page1'));

const Home = () => {
  return (
    <div>
      <h1>Home Page</h1>
      <Page1 />
    </div>
  );
};

export default Home;

  • Advantages:some text
    • Simpler control for small projects.
    • Avoids unnecessary routes by limiting what’s explicitly included.

5. Custom Build Scripts

For advanced scenarios, you can create custom build scripts in your next.config.js file. By overriding the default routing behavior, you can include or exclude specific routes.

module.exports = {
  exportPathMap: async function (defaultPathMap) {
    return {
      '/page1': { page: '/page1' },
      '/page2': { page: '/page2' },
    };
  },
};

  • Advantages:some text
    • Full control over the build process.
    • Useful for applications with unique build requirements.

Additional Tips

  • Optimize Routes Dynamically:
    Use environment variables or configuration files to control which routes are included in builds, allowing flexibility across environments (e.g., staging vs. production).
  • Monitor Build Times:
    Regularly analyze build times and identify routes contributing to delays. Tools like Lighthouse and Next.js analytics can help.
  • Caching Strategies:
    Combine these methods with effective caching to reduce server load and improve performance for dynamic content.

Conclusion

Selective page building in Next.js is an essential technique for managing performance and scalability in modern web applications. By leveraging features such as getStaticPaths, getServerSideProps, and ISR, developers can efficiently tailor the build process to their application's needs. For smaller projects, manual inclusion or dynamic imports may suffice, while advanced use cases can benefit from custom build scripts.By optimizing which pages to pre-build and when to generate them dynamically, you can create robust applications that balance user experience and resource efficiency

Additional Resources

Blogs:

Services:

Contact Us: