Static Exports in Next.js: Deploying Anywhere
Original Content Disclaimer: This article shares my personal experience deploying Next.js applications as static exports. All code snippets are original and provided for educational use.
Next.js Static Exports: Build and Deploy Anywhere
Next.js is famous for server-side rendering, but it's also an incredibly powerful static site generator. By enabling static exports, Next.js compiles your pages into pure static HTML, CSS, and JavaScript files.
This approach opens up possibilities to host your website on zero-cost, high-performance static hosting platforms like GitHub Pages, Netlify, or Firebase Hosting.
How It Works
To enable static exports, update your next.config.js or next.config.mjs config:
<span <span class="vs-keyword">classspan>="vs-keyword">constspan> nextConfig = {
output: 'export',
};
When you run npm run build, Next.js will:
- ✏️Compile your pages and dynamic routes.
- ✏️Read markdown files or fetch APIs at build-time.
- ✏️Generate static HTML and asset files into the
out/directory.
Dynamic Routes in Static Exports
If you have dynamic routes like app/blog/[slug]/page.jsx, Next.js needs to know all the possible paths at build time. We use <span class="vs-function">generateStaticParamsspan>() to provide this list:
<span class="vs-keyword">exportspan> <span class="vs-keyword">asyncspan> <span <span class="vs-keyword">classspan>="vs-keyword">functionspan> <span class="vs-function">generateStaticParamsspan>() {
<span <span class="vs-keyword">classspan>="vs-keyword">constspan> posts = <span class="vs-function">getSortedBlogsDataspan>();
<span <span class="vs-keyword">classspan>="vs-keyword">returnspan> posts.<span class="vs-function">mapspan>((post) => ({
slug: post.slug,
}));
}
Next.js will invoke this function during the build phase and generate a static HTML page for each slug.
Benefits of Static Exports
- ✏️Super Fast Loading: Statically served pages are loaded instantly from CDN caches, improving Core Web Vitals (LCP, INP).
- ✏️Cost Effective: Static files require no node servers running, leading to zero hosting costs.
- ✏️Highly Secure: With no backend server, there are no runtime databases or server vulnerabilities to exploit.
Happy hacking! 🚀