🐶
Next.js

Next.js: `next export` vs `next build` Explained

By Filip on 10/05/2024

Discover the key differences between `next export` and `next build` in Next.js, and learn which approach is best suited for your project's needs.

Next.js: `next export` vs `next build` Explained

Table of Contents

Introduction

This article delves into the differences between two key Next.js commands: next build and next export. While both prepare your application for deployment, they serve distinct purposes and result in different output structures. Let's explore each command and understand when to use them effectively.

Step-by-Step Guide

Next.js offers two main commands for preparing your application for deployment: next build and next export. While they might seem similar, they serve distinct purposes and result in different output structures. Let's break down each command and explore when to use them:

1. next build

  • Purpose: This command creates an optimized production build of your Next.js application. It bundles and minifies your code, optimizes assets, and prepares your app for server-side rendering (SSR) or static site generation (SSG).
  • Output: The build process generates an .next directory containing optimized JavaScript, CSS, and HTML files. This directory is designed to be served by a Node.js server, allowing for dynamic rendering and server-side functionality.
  • When to use:
    • Dynamic content: If your application relies on data fetching, user interactions, or other dynamic elements, next build is the way to go. It enables SSR and SSG, ensuring optimal performance and SEO.
    • Server-side functionality: If you need to utilize server-side features like API routes or middleware, next build is essential.
    • Incremental Static Regeneration (ISR): This feature allows you to update static content after build time. next build is required to enable ISR.

Example (JavaScript):

// This code snippet demonstrates fetching data on the server-side using getServerSideProps
function MyPage({ data }) {
  // ...
}

export async function getServerSideProps() {
  const res = await fetch('https://api.example.com/data');
  const data = await res.json();

  return { props: { data } };
}

2. next export

  • Purpose: This command generates a completely static HTML version of your Next.js application. It pre-renders all pages at build time, creating static HTML files for each route.
  • Output: The export process creates an out directory (configurable) containing static HTML files and any necessary assets. This directory can be served directly by any web server, without needing a Node.js environment.
  • When to use:
    • Static content: If your application consists primarily of static content and doesn't require dynamic rendering or server-side functionality, next export is a good choice. It offers simplicity and fast loading times.
    • Simple deployments: Static HTML files are easy to deploy on various platforms, including static hosting services like Netlify or Vercel.

Example (JavaScript):

// This code snippet demonstrates a simple static page
function MyPage() {
  return (
    <div>
      <h1>Welcome to my static page!</h1>
      <p>This content is pre-rendered at build time.</p>
    </div>
  );
}

export default MyPage;

Key Differences and Considerations:

  • Dynamic vs. Static: next build allows for dynamic rendering and server-side functionality, while next export creates a purely static website.
  • Performance: Both methods can offer excellent performance, but next export might have a slight edge for static content due to its simplicity.
  • Deployment: next build requires a Node.js server, while next export can be deployed on any web server.
  • Features: Some Next.js features, like API routes and ISR, are only available with next build.

Choosing the Right Approach:

The choice between next build and next export depends on your application's specific needs and complexity. If you require dynamic rendering or server-side features, next build is the way to go. For simple static websites, next export offers a lightweight and efficient solution.

Code Example

This code demonstrates Next.js features for dynamic and static content generation. The first example uses next build and getServerSideProps to fetch product data from an API on each request, enabling dynamic rendering. The second example uses next export, getStaticProps, and getStaticPaths to pre-render blog posts at build time, creating static HTML files for faster loading. The choice between these approaches depends on the nature of the content and the desired level of dynamism.

While the provided article explains the concepts well, let's illustrate them with more concrete JavaScript examples:

next build Example - Dynamic Content with API Calls:

// pages/products/[id].js

function Product({ productData }) {
  // Render product details using productData
  return (
    <div>
      <h1>{productData.name}</h1>
      <p>{productData.description}</p>
      {/* ... */}
    </div>
  );
}

export async function getServerSideProps(context) {
  const { id } = context.query;
  const res = await fetch(`https://api.example.com/products/${id}`);
  const productData = await res.json();

  return { props: { productData } };
}

export default Product;

Explanation:

  1. Dynamic Route: The file name [id].js defines a dynamic route, allowing us to fetch and display different products based on the ID in the URL.
  2. getServerSideProps: This function runs on the server during each request. It fetches product data from an external API based on the product ID.
  3. Data Passing: The fetched productData is passed as a prop to the Product component, enabling dynamic rendering of product details.

next export Example - Static Blog Page:

// pages/blog/[slug].js

function BlogPost({ postData }) {
  // Render blog post content using postData
  return (
    <div>
      <h1>{postData.title}</h1>
      <div dangerouslySetInnerHTML={{ __html: postData.content }} />
      {/* ... */}
    </div>
  );
}

export async function getStaticProps(context) {
  const { slug } = context.params;
  // Fetch blog post data from a CMS or local markdown files
  const postData = await getBlogPostData(slug);

  return { props: { postData } };
}

export async function getStaticPaths() {
  // Get a list of all blog post slugs
  const slugs = await getAllBlogPostSlugs();

  return {
    paths: slugs.map((slug) => ({ params: { slug } })),
    fallback: false,
  };
}

export default BlogPost;

Explanation:

  1. Static Generation with Dynamic Routing: We use getStaticProps and getStaticPaths to pre-render blog posts at build time.
  2. getStaticPaths: This function defines the list of paths (slugs) to be statically generated.
  3. getStaticProps: For each path, this function fetches the corresponding blog post data.
  4. Static HTML Generation: Next.js generates static HTML files for each blog post during the build process.

Choosing the Right Approach:

  • Use next build when you need dynamic content, server-side rendering, or features like API routes and ISR.
  • Use next export for static websites with content that doesn't change frequently, prioritizing simplicity and fast loading times.

Additional Notes

Hybrid Approaches and Incremental Static Regeneration (ISR):

  • Combining SSG and SSR: Next.js allows you to use both getStaticProps and getServerSideProps in your application. This enables a hybrid approach where some pages are statically generated, while others are rendered dynamically on the server.
  • Incremental Static Regeneration (ISR): This powerful feature allows you to update static content after build time. With ISR, you can set a revalidation time for a page. When a request comes in after the revalidation time has elapsed, Next.js will regenerate the page in the background and serve the updated content on subsequent requests. This provides a balance between static site generation's performance benefits and the ability to keep content fresh.

Deployment Considerations:

  • Hosting Platforms:
    • next build: Requires a Node.js environment. Popular options include Vercel, Netlify (with Node.js support), AWS EC2, and Heroku.
    • next export: Can be deployed on any static hosting platform, such as Netlify, GitHub Pages, AWS S3, or Firebase Hosting.
  • Custom Server: You can create a custom Node.js server to handle routing, middleware, and other server-side logic when using next build.

Performance Optimization:

  • Automatic Image Optimization: Next.js automatically optimizes images during the build process, resizing and serving them in modern formats like WebP.
  • Code Splitting and Bundling: Next.js optimizes code splitting and bundling to ensure that only the necessary JavaScript is loaded for each page, improving initial load times.
  • Caching: Leverage caching mechanisms like CDNs and browser caching to further enhance performance.

Additional Features:

  • API Routes: Create serverless API endpoints within your Next.js application using API routes.
  • Middleware: Intercept and modify incoming requests with middleware functions.
  • Internationalization: Build multilingual websites with built-in internationalization routing and language detection.

Community and Resources:

  • Next.js Documentation: The official Next.js documentation provides comprehensive information on all features and APIs.
  • Next.js Learn: Interactive tutorials and examples to help you get started with Next.js.
  • Next.js GitHub Repository: Explore the source code and contribute to the Next.js project.
  • Next.js Community: Join the active Next.js community on GitHub, Discord, and Twitter for support and discussions.

By understanding the nuances of next build and next export, you can make informed decisions about the best approach for your Next.js projects, ensuring optimal performance, scalability, and developer experience.

Summary

Feature next build next export
Purpose Creates optimized production build for SSR or SSG. Generates a static HTML version of your app.
Output .next directory with optimized JS, CSS, and HTML. out directory (configurable) with static HTML files and assets.
Use Cases Dynamic content, server-side functionality, ISR. Static content, simple deployments.
Performance Excellent, especially with SSR and SSG. Excellent, especially for static content.
Deployment Requires a Node.js server. Can be deployed on any web server.
Features Supports all Next.js features, including API routes and ISR. Limited to static features; no API routes or ISR.
Example Server-side data fetching with getServerSideProps. Simple static page with pre-rendered content.

Choosing the right command depends on your application's needs:

  • Dynamic content or server-side functionality? Use next build.
  • Simple static website? Use next export.

Conclusion

Next.js provides developers with powerful options for building and deploying web applications. Understanding the core differences between next build and next export is crucial for making informed decisions that align with your project's specific requirements.

Dynamic Content and Server-Side Features:

If your application demands dynamic content generation, server-side rendering, or utilizes features like API routes and Incremental Static Regeneration (ISR), next build is the optimal choice. It empowers you to create interactive and data-driven experiences while maintaining excellent performance and SEO benefits.

Static Websites and Simplicity:

For projects that primarily consist of static content and prioritize simplicity and fast loading times, next export offers a compelling solution. By generating static HTML files, you can easily deploy your website on a wide range of hosting platforms without the need for a Node.js environment.

Hybrid Approaches and Flexibility:

Next.js also allows for hybrid approaches, combining static site generation with server-side rendering to cater to diverse content needs within a single application. This flexibility empowers developers to tailor their strategies based on the specific requirements of each page or section.

Ultimately, the choice between next build and next export hinges on your project's unique goals and technical demands. By carefully considering the trade-offs and leveraging the strengths of each approach, you can build high-performance, scalable, and user-friendly web applications with Next.js.

References

Were You Able to Follow the Instructions?

😍Love it!
😊Yes
😐Meh-gical
😞No
🤮Clickbait