26

So, I have a NextJS application and the way I have been building links is through component. For eg: <Link href="/my-page"><a>My page</a></Link>. I have built the whole app with this pattern for However, when I did an export to generate a static site, it created the out folder with pages with .html extension. This is now a problem, since, say a link might be pointing to /my-page but the actual page is /my-page.html. What's the right way of handling this issue? Does NextJS allows us to do anything in this situation or do I need to go back and code all my tags using /my-page.html links?

Thanks.

Blueboye
  • 1,374
  • 4
  • 24
  • 49

1 Answers1

30

The default in next.js for static generation is to map this code:

/pages/p1.tsx

to this file:

/p1.html

The problem with that is that a link to /p1 will work when you use the next server, and will fail when you're serving static files.

If you enable this, in next.config.js:

module.exports = {trailingSlash: true,}

Then you'll get a different file:

/p1/index.html

And on most generic web servers (Apache out of the box, for example), you get this behavior:

/p1 - redirects to /p1/
/p1/ - serves /p1/index.html
/p1/index.html - serves /p1/index.html

So I think module.exports = {trailingSlash: true,} gets you the behavior you're expecting.

(@jdaz's link to the other answer is definitely useful for this, but that question was very specifically about configuring .htaccess, so I'm repeating a similar answer here)

James Moore
  • 8,636
  • 5
  • 71
  • 90
  • `module.exports = {trailingSlash: true,}` produces `Error occurred prerendering page "/auth/restore". Read more: https://nextjs.org/docs/messages/prerender-error TypeError [ERR_INVALID_URL]: Invalid URL ` – user64204 Jul 22 '22 at 11:25
  • 1
    This mostly shifts the complexity of the solution to the (web) serving logic. Is there not a native (Next.js) solution? – Bertrand Caron Jan 24 '23 at 00:15