In the world of modern web development, static exports are a powerful tool, and Next.js static export is no exception. Next.js provides a robust framework for creating static sites, allowing you to generate static HTML files from your dynamic pages. This process involves converting your pages into static HTML files, which can then be served without the need for a server-side environment.
This blog will delve into the fundamentals of static exports, how they work in Next.js, and the benefits they offer.
Next.js static export enables you to pre-render your app into static HTML files. By running the export command, Next.js processes your pages and generates static HTML files for each page. This approach contrasts with server side rendering, where the HTML is generated on the fly for each incoming request.
Performance: Serving static HTML files is faster since they can be delivered directly by a web server without additional processing.
Scalability: Static sites can handle high traffic with ease because they do not rely on server-side processing.
SEO Friendly: Static HTML pages are more SEO-friendly because they can be fully crawled by search engines.
Generating static HTML files in Next.js involves a specific build process. The key steps include using the next build and next export commands.
The next build command compiles your application and prepares it for production. After building your app, you use the next export command to generate static HTML files.
1next build 2next export
The next export command takes your built application and outputs static HTML files for each page in the pages directory. These files are placed in the out folder, which can then be deployed to any static host.
Creating static HTML files involves converting your dynamic Next.js pages into static HTML files that can be served without a Node.js server. This is done using the export default function to define each page's component.
Each page in your Next.js app is defined using the export default function. This function exports the component that represents the page.
1// pages/index.js 2export default function HomePage() { 3 return <div>Welcome to the Home Page</div> 4}
When you run the next export command, Next.js processes each of these components and generates a corresponding static HTML file.
The pages directory is crucial in the Next.js static export process. Each file in this directory corresponds to a route in your static site. For example, pages/about.js would generate an about.html file in the out directory.
Static exports work well for content that doesn't change frequently, but they can also handle dynamic logic to some extent.
Dynamic routes in Next.js are typically handled using the [param].js file naming convention. For example, pages/posts/[id].js handles routes like /posts/1, /posts/2, etc. However, to use these in a static export, you need to predefine the routes.
1// next.config.js 2module.exports = { 3 exportPathMap: async function ( 4 defaultPathMap, 5 { dev, dir, outDir, distDir, buildId } 6 ) { 7 return { 8 '/': { page: '/' }, 9 '/about': { page: '/about' }, 10 '/posts/1': { page: '/posts/[id]', query: { id: 1 } }, 11 '/posts/2': { page: '/posts/[id]', query: { id: 2 } }, 12 } 13 }, 14}
For pages that fetch data at build time, you can use getStaticProps to generate static HTML. This allows you to include dynamic content in your static pages.
1// pages/posts/[id].js 2export async function getStaticProps({ params }) { 3 const res = await fetch(`https://api.example.com/posts/${params.id}`) 4 const post = await res.json() 5 6 return { 7 props: { 8 post, 9 }, 10 } 11} 12 13export default function Post({ post }) { 14 return ( 15 <div> 16 <h1>{post.title}</h1> 17 <p>{post.body}</p> 18 </div> 19 ) 20}
The pages directory is the backbone of your Next.js project, determining the structure of your static site. Each file within this directory corresponds to a route in your application. Here’s how you can efficiently organize your pages directory for optimal performance and maintainability.
Consistent Naming Conventions: Use clear and consistent naming conventions for your files and folders. For example, use about.js for the About page and contact.js for the Contact page.
Nested Routes: Organize related pages using nested folders. For instance, you can group user-related pages under a user folder:
1pages/ 2├── index.js 3├── about.js 4├── contact.js 5├── user/ 6 ├── index.js 7 ├── profile.js 8 ├── settings.js
1// pages/posts/[id].js 2export default function Post({ post }) { 3 return ( 4 <div> 5 <h1>{post.title}</h1> 6 <p>{post.body}</p> 7 </div> 8 ) 9}
Static exports provide significant performance benefits, but there are additional strategies to optimize your static site further.
The next/image component provides built-in image optimization, ensuring that images are served in the most efficient format and size.
1import Image from 'next/image' 2 3export default function HomePage() { 4 return ( 5 <div> 6 <h1>Welcome to the Home Page</h1> 7 <Image 8 src="/images/hero.jpg" 9 alt="Hero Image" 10 width={500} 11 height={300} 12 /> 13 </div> 14 ) 15}
Static HTML export (next export) ensures that your pages are pre-rendered and served as static HTML files, reducing load times and improving SEO.
Next.js automatically divides your code into tiny bundles that are loaded only when necessary. This increases both initial load times and overall performance.
Custom loaders and proper configuration can tailor your static site to specific needs and improve performance.
Custom loaders can handle specific resource types or perform unique optimizations. For example, you might use a custom loader for SVG files:
1// next.config.js 2module.exports = { 3 webpack(config) { 4 config.module.rules.push({ 5 test: /\.svg$/, 6 use: ['@svgr/webpack'], 7 }) 8 return config 9 }, 10} 11
Your next.config.js file is crucial for customizing the behavior of your Next.js app. Here’s an example configuration that optimizes your static site:
1// next.config.js 2module.exports = { 3 exportPathMap: async function ( 4 defaultPathMap, 5 { dev, dir, outDir, distDir, buildId } 6 ) { 7 return { 8 '/': { page: '/' }, 9 '/about': { page: '/about' }, 10 '/contact': { page: '/contact' }, 11 } 12 }, 13 images: { 14 domains: ['example.com'], 15 }, 16 reactStrictMode: true, 17}
This configuration:
• Defines the export path map for static export.
• Specifies image domains for optimization.
• Enables React strict mode for development.
The out folder, generated by the next export command, contains all your static files. Ensure it’s correctly configured for deployment to your static host.
When you run the next export command, Next.js generates static HTML files and assets, placing them in a special directory called the out folder. Understanding the structure and contents of this directory is crucial for deploying your static site effectively.
The out directory is the output folder where all the generated static HTML files, CSS, JavaScript, and other assets are stored after running the next export command. This directory is ready for deployment to any static host.
Static HTML Files: Each page in your pages directory corresponds to an HTML file in the out folder.
Assets: Includes all the necessary assets such as images, fonts, and CSS files.
Organized Structure: The structure of the out folder mirrors the structure of your pages directory.
1out/ 2├── index.html 3├── about.html 4├── contact.html 5├── _next/ 6│ ├── static/ 7│ └── ...
There are several options for deploying your Next.js static site, each with its own set of benefits.
Static hosts are a popular choice for deploying static sites because they are easy to set up and usually offer high performance and scalability. Examples include Vercel, Netlify, and GitHub Pages.
1# Install Vercel CLI 2npm install -g vercel 3 4# Deploy to Vercel 5vercel
1# Install Netlify CLI 2npm install -g netlify-cli 3 4# Deploy to Netlify 5netlify deploy
1# Initialize a new GitHub repository 2git init 3git add . 4git commit -m "Initial commit" 5git remote add origin <your-repo-url> 6 7# Push to GitHub 8git push -u origin main 9 10# Deploy to GitHub Pages 11gh-pages -d out
For more control over your deployment, you might choose to serve your static site with a Node.js server. This approach allows you to customize your server configuration and add server-side logic if needed.
1const express = require('express') 2const path = require('path') 3const app = express() 4 5app.use(express.static(path.join(__dirname, 'out'))) 6 7app.get('*', (req, res) => { 8 res.sendFile(path.join(__dirname, 'out', 'index.html')) 9}) 10 11app.listen(3000, () => { 12 console.log('Server is running on http://localhost:3000') 13})
While deploying and serving a static site with Next.js is generally straightforward, there are some common challenges you may encounter.
Some Next.js features are not supported in static exports, such as server side rendering and certain dynamic routes. To handle these, you might need to adjust your code or use client-side rendering for those specific features.
Server Side Rendering: Convert server-rendered pages to static pages using getStaticProps.
Dynamic Routes: Pre-generate dynamic routes using the exportPathMap function in next.config.js.
Dynamic logic can be tricky in a static site. Consider using APIs or client-side JavaScript to handle dynamic content.
1// Fetch data client-side 2useEffect(() => { 3 fetch('/api/data') 4 .then(response => response.json()) 5 .then(data => setData(data)) 6}, [])
Large projects may result in long build times. Optimize your build process by:
Code Splitting: Ensure your code is split into smaller bundles.
Optimizing Images: Use next/image for automatic image optimization.
Reducing JavaScript Size: Minimize the amount of JavaScript loaded by removing unused dependencies.
Mastering Next.js static export allows you to build high-performance, scalable, and SEO-friendly static sites. By understanding the out directory, utilizing efficient deployment options, and addressing common challenges, you can ensure a smooth and effective deployment process.
Whether you choose a static host like Vercel or Netlify, or serve your site with a Node.js server, Next.js provides the flexibility and power needed for modern web development. With these insights, you are well-equipped to create and deploy robust static sites using Next.js.
Tired of manually designing screens, coding on weekends, and technical debt? Let DhiWise handle it for you!
You can build an e-commerce store, healthcare app, portfolio, blogging website, social media or admin panel right away. Use our library of 40+ pre-built free templates to create your first application using DhiWise.