Rendering on Client Only in NextJS

Here are a couple ways to render a React component in the browser only when using NextJS.

App Router in Next 13

Next 13 introduced the new "app" router which supports React Server Components (RSC). At the same time, it made clear distinctions for what components weren't server components. And if you're not server, your client.

In app router, to make a component render on the client only, add a directive at the top of your module file, as in my-component.tsx:

'use client'

import React from 'react'
export interface MyComponentProps {}
export function MyComponent(props: MyComponentProps) {
  return <div>client only, baby!</div>
}

Pages Router

Pages router still exists in Next 13, and it has existed since the start. When "use client" is unavailable, the way to make a client render only in the browser is to dynamically import it. Use the next/dynamic wrapper around the standard esm dynamic import(). For example, import the above-mentioned my-component as in this my-component-dynamic.tsx file:

import dynamic, { DynamicOptions } from 'next/dynamic'
import { MyComponentProps } from './my-component'

export const MyComponent = dynamic(
  import('./my-component')
    .then((mod) => mod.MyComponent)
    .catch((err) =>
      console.error(`Failed to load MyComponent!`, err),
    ) as DynamicOptions<MyComponentProps>,
  {
    ssr: false,
  },
)

I would not render on the build server. I would not render on the runtime server. Say! I would render on the client.