Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Nextjs, how to programatically trigger server side rendering?

Tags:

next.js

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.

like image 266
flo Avatar asked Aug 06 '19 13:08

flo


People also ask

Is Next.js server-side rendering by default?

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.

Can I use Next.js without server-side rendering?

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.

What is difference between getInitialProps and getServerSideProps?

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).

What is difference between getStaticProps and getServerSideProps?

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.


1 Answers

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.

like image 99
I'm Joe Too Avatar answered Dec 14 '22 09:12

I'm Joe Too