Conditionally import module using next js dynamic import, SSR doesn't work

Viewed 4000

I've a component which I am dynamically importing using dynamic from nextjs. And that too I want to download the bundle based on a flag that I am setting in my code (loadWirelessBundle flag in below code block). So it works fine in terms of downloading the bundle but and rendering the component BUT it doesn't do server side rendering of the component (when loadWirelessBundle is true) even I am passing ssr = true. Does anyone know why it doesn't do server-side rendering?

const WirelessPrepaid = loadWirelessBundle ? dynamic(() => import("../wireless-prepaid"), { ssr: true }) : () => null;

Is there something I am missing in terms of understanding dynamic import with nextjs? Could someone please help? Thanks!

2 Answers

You need to do the import at the top level

// this goes at the top level of the module
const WirelessPrepaidDynamicComponent = dynamic(() => import("../wireless-prepaid"));

// this can be placed wherever you need it

const WirelessPrepaid = loadWirelessBundle ? WirelessPrepaidDynamicComponent  : () => null;


First of all, it is not required to pass ssr as true explicitly, by default it is enabled only.

Secondly, it might be the case that the value of loadWirelessBundle is set on the client-side rather than on the server-side, therefore the component is getting imported on the client-side. So we might have to set its value on the server-side and see if it works.

Related