DEV Community

sadnessOjisan
sadnessOjisan

Posted on • Updated on

Deploy Anywhere Next.js app using SSG and Dynamic routing

SSG stands for Static Site Generation and Next.js recommend it officially. When I look at this term first, I thought "it generates just a simple HTML, I can deploy it anywhere". But that was a misunderstanding.

I can't handle it as simple HTML

The reason is <Link> tag. If you click <Link href-"about">about</Link>, It navigates you to /about. Not /about.html. That's why In some cases, this routing resource may not be there if you didn't deploy it to so kindful infrastructure(for example Vercel). That's why if you reload this URL, you can't get any resources. No page is shown. In many cases, if you want to open this page directly, you should rewrite URL routing to *.html.

rewrite for Dynamic routing

The above problem is solved if you write rewrite config. For example

/about -> /about.html
/me -> /me.html
Enter fullscreen mode Exit fullscreen mode

But how do you write a dynamic HTML page's route config? NextJS can generate a page and URL at build time depends on some outer resources(for example API). The URL will be like /user/1, /user/posts/1, and so on. If you know all endpoints and data, you may be able to write all. But this is so hard and in many cases impossible.

Naive Solutions

If you deploy to good infrastructure, they may provide some config to rewrite dynamic URL. For example netlify.toml, firebase functions, lambda and cloud front, amplify console and so on.

But this solution depends on your environment and a little difficult. How can I deploy it anywhere easily?

Solution: Use trailingSlash config

The simple solution is just to use trailingSlash in next.config.js.

 trailingSlash: true,
Enter fullscreen mode Exit fullscreen mode

https://nextjs.org/docs/api-reference/next.config.js/exportPathMap#adding-a-trailing-slash

That's all! This navigates to *.html when you click Link. Then you can treat your SSG site as a simple static website. You can deploy it anywhere.

Top comments (2)

Collapse
 
9renpoto profile image
Keisuke Umeno
-/abount -> /abount.html
+/about -> /abont.html
Enter fullscreen mode Exit fullscreen mode
Collapse
 
sadnessojisan profile image
sadnessOjisan

Thank you teach me.