0
0
NextJSframework~5 mins

Client-only modules in NextJS

Choose your learning style9 modes available
Introduction

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.

When you want to use browser-only APIs like localStorage or window.
When a module depends on the DOM and breaks if run on the server.
When you want to load a component only after the page loads in the browser.
When you want to improve performance by not running heavy code on the server.
Syntax
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.

Examples
This loads the Map component only in the browser because it uses browser APIs.
NextJS
import dynamic from 'next/dynamic';

const Map = dynamic(() => import('./Map'), { ssr: false });
Simple example to load a component only on the client side.
NextJS
import dynamic from 'next/dynamic';

const ClientOnlyComponent = dynamic(() => import('./ClientOnlyComponent'), { ssr: false });
Sample Program

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.

NextJS
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>;
}
OutputSuccess
Important Notes

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.

Summary

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.