export static res js

What is Export Static Res JS?

Export Static Res JS is a feature of Next.js that allows you to easily export a pre-rendered version of your application to static HTML and JavaScript files. This means that you can host your website on any static hosting provider, such as GitHub Pages or Netlify, without the need for a server or backend infrastructure.

How to use Export Static Res JS in Next.js?

To use Export Static Res JS in Next.js, you need to add a script to your package.json file:


"scripts": {
  "build": "next build",
  "export": "next export"
}

Then, you can run the following command to generate static HTML and JavaScript files:


npm run build
npm run export

After running the above commands, you will find a new folder named "out" in your project root directory. This folder contains all the static HTML and JavaScript files that you can host on any static hosting provider.

Export Static Res JS with dynamic routes

Next.js allows you to define dynamic routes for your application. To export these dynamic routes, you need to create a file named "next.config.js" in your project root directory and add the following code:


module.exports = {
  exportPathMap: async function (
    defaultPathMap,
    { dev, dir, outDir, distDir, buildId }
  ) {
    return {
      '/post/1': { page: '/post/[id]', query: { id: '1' } },
      '/post/2': { page: '/post/[id]', query: { id: '2' } },
      '/post/3': { page: '/post/[id]', query: { id: '3' } },
    }
  }
}

In the above code, we are defining three dynamic routes for our application. After adding this code to your project, you can run the following command to export your application with dynamic routes:


npm run build
npm run export

After running the above commands, you will find a new folder named "out" in your project root directory. This folder contains all the static HTML and JavaScript files, including the dynamic routes, that you can host on any static hosting provider.

Conclusion

Export Static Res JS is a powerful feature of Next.js that allows you to easily export a pre-rendered version of your application to static HTML and JavaScript files. This feature can help you host your website on any static hosting provider without the need for a server or backend infrastructure. With dynamic routes support, Export Static Res JS becomes even more powerful and flexible to use.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe