mbappai
mbappai

Reputation: 579

How to disable Nextjs from pre-rendering a page?

How can I truly CSR (client-side render) some pages in my NextJs application?

The documentation says that the presence of either getServerSideProps or getStaticSiteProps in a page would make it pre-render on the server per request or at build time respectively.

Yet again, with the advent of automatic static optimisation NextJs determines automatically whether or not to pre-render a statically in the absence of getServerSideProps or getInitialProps — If I understand this statement currently, it means that all pages that don't export the aforementioned server-side functions, will be be statically generated on the server

So my question now is how do I truly render on client side only for pages like dashboard, without having nextjs automatically pre-render due to automatic static optimization?

Upvotes: 7

Views: 13538

Answers (2)

shrekuu
shrekuu

Reputation: 2262

Yes. Like other answers mentioned, I created a global component NoSSR.tsx file.

import dynamic from 'next/dynamic';
import React from 'react';

const NoSSR = ({ children }: { children: React.ReactNode }) => <React.Fragment>{children}</React.Fragment>;

export default dynamic(() => Promise.resolve(NoSSR), {
  ssr: false,
});

Whenever I want to force a component to only render in the browser, say this CompA.tsx:

// This line becomes useless actually since we do not prerender it on the server. Omit it if you like.
'use client';  

export default function CompA() {
  return <div>CompA</div>;
}

I just wrap that component with this component like this (this code can appear on both server-side components and client-side components):

...
<NoSSR>
  <CompA />
</NoSSR>
...

Upvotes: 0

Shubham Waje
Shubham Waje

Reputation: 923

You can disable SSR for a specific component while exporting it.

const NoSSRYourComponent = () => {
    return (
        // ... NoSSRYourComponent code
    )
}

// export it with SSR disabled
const YourComponent = dynamic(() => Promise.resolve(NoSSRYourComponent), {
  ssr: false,
})

export default YourComponent

Upvotes: 10

Related Questions