We know that Router.push() triggers client-side rendering. But how can I programatically trigger server-side rendering to a page?
Example: I have a login modal which on submit sends a api call to check user data. Once I got the info that the user is ok, I want to load a page but via a server-side rendering.
By default, Next.js pre-renders every page. This means that Next.js generates HTML for each page in advance, instead of having it all done by client-side JavaScript. Pre-rendering can result in better performance and SEO. Each generated HTML is associated with minimal JavaScript code necessary for that page.
You can use the ssr: false object to disable server-side rendering of your dynamically imported component, as shown below. Or else, you can create a wrapper component called NonSSRWrapper and then enclose any page in that component to disable SSR.
getInitialProps will run on the server during the initial page load and, subsequently, run in the browser if you make client-side transition to other parts of the application. However, getServerSideProps will only run on the server and never in the browser (even if you make client-side navigation, or refresh the page).
getStaticProps(): A method that tells the Next component to populate props and render into a static HTML page at build time. getServerSideProps(): A method that tells the Next component to populate the props and render into a static HTML page at run time.
If you want to server-side render a page, you can't navigate to it using Router
or Link
- you should use native a
or window.location
functionality. In your case, after you get the response from the API, you want to trigger a redirect (as if the user clicked a link), so you should call:
window.location.href = "https://{yourDestination}"
This will force a request to the server. As you've experienced, Router
and Link
attempt to keep everything on the client side.
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