Client-only modules let you run code only in the browser, not on the server. This helps when you use features that need the browser, like window or document.
Client-only modules in NextJS
import dynamic from 'next/dynamic'; const ClientComponent = dynamic(() => import('./ClientComponent'), { ssr: false });
Use dynamic from Next.js to load modules only on the client.
Setting ssr: false disables server-side rendering for that module.
Map component only in the browser because it uses browser APIs.import dynamic from 'next/dynamic'; const Map = dynamic(() => import('./Map'), { ssr: false });
import dynamic from 'next/dynamic'; const ClientOnlyComponent = dynamic(() => import('./ClientOnlyComponent'), { ssr: false });
This example shows a page that loads a ClientOnly component only in the browser. The component uses window.innerWidth, which is not available on the server. Using dynamic with ssr: false prevents errors and shows the width after loading.
import dynamic from 'next/dynamic'; import React from 'react'; const ClientOnly = dynamic(() => import('./ClientOnly'), { ssr: false }); export default function Home() { return ( <main> <h1>Welcome to Client-only Modules Demo</h1> <ClientOnly /> </main> ); } // ClientOnly.js import React, { useEffect, useState } from 'react'; export default function ClientOnly() { const [width, setWidth] = useState(0); useEffect(() => { setWidth(window.innerWidth); }, []); return <p>Window width is: {width}</p>; }
Client-only modules help avoid errors from using browser-only features on the server.
Remember to import dynamic from 'next/dynamic' to use this feature.
Use client-only modules to improve user experience by loading interactive parts only in the browser.
Client-only modules run only in the browser, not on the server.
Use dynamic with ssr: false to load these modules.
This helps when using browser APIs or improving performance.