Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deal with NextJS exporting files with .html extension but in<Link> there is no .html

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.

like image 938
Blueboye Avatar asked Jul 12 '20 22:07

Blueboye


People also ask

Does Nextjs use HTML?

Next. js has two forms of pre-rendering: Static Generation and Server-side Rendering. The difference is in when it generates the HTML for a page. Static Generation (Recommended): The HTML is generated at build time and will be reused on each request.

What is static export in next JS?

next export allows you to export your Next. js application to static HTML, which can be run standalone without the need of a Node. js server. It is recommended to only use next export if you don't need any of the unsupported features requiring a server.

What is static export?

The static export is an advanced OpenCms feature, that allows to gain an important performance improvement by mirroring pages and other resources into the real file system of the server.


1 Answers

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)

like image 55
James Moore Avatar answered Sep 19 '22 08:09

James Moore