Nighon
Nighon

Reputation: 1074

How to generate .html files for route [slug] in Next.js app?

I have a Next.js (version 13.4.5) app with a dynamic route /blog/[slug]. I wish to export the app as a static website. Here is the directory structure:

/app
  /blog
    /[slug]
      page.jsx
    page.jsx
  layout.jsx
  globals.css
  ...

and content of next.config.js:

const nextConfig = {
  output: 'export',
  trailingSlash: true,
}

module.exports = nextConfig

After I run command npm run build, the generated files in /out directory are as following:

/out
  /.next
  /404
  /blog
    index.html
    index.txt
  404.html
  index.html
  index.txt
  ...

There are no .html files generated for the route /blog/[slug], which is not the same as described in the official document:

When running next build, Next.js generates the static export into the out folder. Using next export is no longer needed. For example, let's say you have the following routes:

/

/blog/[id]

After running next build, Next.js will generate the following files:

/out/index.html

/out/404.html

/out/blog/post-1.html

/out/blog/post-2.html

In previous version I can use getStaticPaths and getStaticProps to pre-render pages. But these methods are not supported in new version with new App Router.

How can I generate .html files in new version ("next": "13.4.5",) for route /blog/[slug]?

Upvotes: 2

Views: 2997

Answers (1)

Yilmaz
Yilmaz

Reputation: 49709

you need to use generate-static-params

// Return a list of `params` to populate the [slug] dynamic segment
export async function generateStaticParams() {
  const posts = await fetch('https://.../posts').then((res) => res.json())
 
  return posts.map((post) => ({
    slug: post.slug,
  }))
}
 
// Multiple versions of this page will be statically generated
// using the `params` returned by `generateStaticParams`
export default function Page({ params }) {
  const { slug } = params
  // ...
}

Upvotes: 3

Related Questions