I am trying to make a single-page application in NextJS, but I am starting to think this is not possible. Can anyone show me how?
My first attempt was to use a Hash Router:
<HashRouter>
<div>
<NavLink to="/">Home</NavLink>
<NavLink to="/purchaseComplete">Purchase Complete</NavLink>
</div>
<div>
<Route exact path="/" Component={Default} />
<Route path="/purchaseComplete" Component={PurchaseComplete} />
</div>
</HashRouter>
But in the browser I see "Invariant failed: Browser history needs a DOM"
I then tried to use a StaticRouter:
<StaticRouter location="/" context={staticContext}>
<div>
<NavLink to="/">Home</NavLink>
<NavLink to="/purchaseComplete">Purchase Complete</NavLink>
</div>
<div>
<Switch>
<Route exact path="/" Component={Default} />
<Route path="/purchaseComplete" Component={PurchaseComplete} />
</Switch>
</div>
</StaticRouter>
This renders the two links, but nothing happens when you click them.
In the NextJS tutorials, they talk about SPA's in the beginning, but then they only show you how to make apps with multiple pages.
I am starting to think it's not possible to build an SPA in NextJS. Can anyone confirm this? Or can someone show me how to build an SPA in Next JS?
It turns out that Next.Js is intended to be used for multi-page apps. The author explains how it is possible to use the React Router to make a single-page app with Next.JS. However, he also says the Next.JS authors responded and said they don't intend for Next.JS to be used this way!
When creating a new Next.js application, the framework starts with a homepage that includes some sample content. Additionally, its conventionality includes the Next.js Head component out of the box, first imported at the top of the file: We’re making our Head component available in this instance, then adding a title, description, and a favicon.
Next.js is a web framework that sits on top of React, providing a bunch of features out of the box that can take our applications to another level. In the example of our traditional SPA, we had a single index.html file.
While you can’t do this out of the box with Next.js, there are plugins to help, such as the Next.js Sitemap Generator or a custom approach like the one I added to my Next.js WordPress Starter.
I found a blog post that answers this question: https://dev.to/toomuchdesign/next-js-react-router-2kl8
It turns out that Next.Js is intended to be used for multi-page apps.
The author explains how it is possible to use the React Router to make a single-page app with Next.JS. However, he also says the Next.JS authors responded and said they don't intend for Next.JS to be used this way!
I totally agree with the author, and am using his approach in my app. I want server-side rendering from NextJS, but also want it to be a single-page application.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With