Part 46: Exporting Your Next.js App as a Static Website

[App] Deployment

[App] Deployment

If you don't require full-stack features like server-side rendering in your Next.js application, you can choose to export it as a static website. This approach allows you to deploy your app to any standard web server with ease. Let's walk through the process of creating a static export of your Next.js app.

Configuring Next.js for Static Export

By default, Next.js apps are set up to run with-side capabilities. However, to generate a static version, you need to modify the Next.js configuration file named next.config.js.

Here's how you can configure it:

  1. Modify next.config.js: You need to export an object using the CommonJS convention. To guide your editor, you can import the NextConfig type from the next module. This will help you understand which properties are available in the configuration object.

  2. Set the Output Option: Add the output property to this object and set it to "export". According to the documentation, this setting will create an out directory containing only static HTML, CSS, and JavaScript files.

/** @type {import('next').NextConfig} */
const nextConfig = {
    output: 'export',
};

export default nextConfig;

Building and Testing Locally

Once your configuration is set, you can proceed to build your project:

  • Run the Production Build: Use the command npm run build. Unlike the typical build process that generates files in the .next folder, this will create a new folder named out containing all the static files such as index.html and other pages.

  • Testing Locally: Before deploying, it's a good idea to test the static website locally. You can use a simple local server to do this. An easy way is to use an npm package called serve, which can be run directly with npx:

npx serve@latest out

This command will start a local server on port 3000 by default, serving the static files from the out folder. This server is a basic HTTP server, unlike the Next.js server, and is designed to serve static content.

Deploying Your Static Site

With your static files ready and tested, you can deploy the out folder to any web hosting service. This process involves uploading the contents of the out folder to your server. Make sure to include /out/ in your .gitignore file, as it contains generated files that do not need to be version-controlled:

/out/

Conclusion

Switching your Next.js application to a static export is straightforward and can significantly simplify the deployment process if server-side features are not necessary for your project. This method leverages the static site generation capabilities of Next.js, ensuring your site loads quickly and efficiently. In future posts, we'll explore how to deploy these static files to various hosting platforms.

Last updated