How to disable Nextjs from pre-rendering a page?
Asked Answered
M

2

6

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?

Magnien answered 28/11, 2022 at 7:42 Comment(0)
C
9

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
Comstock answered 28/11, 2022 at 7:55 Comment(5)
Thank you for your reply Shubham, but can you please provide a little more context to this answer or better yet a reference to a doc? ThanksMagnien
So the main motto behind disabling ssr is to dynamically load a component on the client side. This is useful if a component relies on browser APIs like window or you want to render it client side specifically. refer docs for more infoComstock
Either you can import it using dynamic but exporting it dynamically will allow you to directly use that component without disabling ssr every time you import.Comstock
Ahh yes! After looking at the doc, I am convinced that this is the solution for my problem. Thanks a lot Shubham!Magnien
Thank you! you finally solved my problem with export errorsVitrics
G
0

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>
...
Gabrila answered 28/9 at 10:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.