Next.js: Disable Server-Side Rendering on Specific Pages

Updated: January 9, 2023 By: Khue Post a comment

There may be situations where you want to disable server-side rendering (SSR) on one or some specific pages of your Next.js application, such as you get some warnings or errors when using a third-party library due to SSR or you want a page to behave like a normal React page without SSR in any way. Luckily, Next.js gives us a built-in function to do so: the dynamic() function that can be imported from next/dynamic. Alternatively, you can use a third-party package named react-no-ssr. Let’s explore these two different techniques in this practical article.

Using the dynamic() function

What we need to do is to create a wrapper component named NoSSRWrapper. Just wrap any page you want to disable SSR in that component.

Create a new folder called components in your project (if this folder doesn’t exist yet), then create a file name no-ssr-wrapper.js right there:

import dynamic from 'next/dynamic'
import React from 'react'

const NoSSRWrapper = props => (
  <React.Fragment>{props.children}</React.Fragment>
)

export default dynamic(() => Promise.resolve(NoSSRWrapper), {
  ssr: false
})

Let’s say we want to disable SSR on a feed page in the pages folder:

// pages/feed.js
import NoSSRWrapper from "../components/no-ssr-wrapper";

const Feed = props => {
  return <NoSSRWrapper>
    {/* ... */}
  </NoSSRWrapper>
}

Using the react-no-ssr package

This package provides a simple and quick solution to deal with client-only components/pages in Next.js.

Install:

npm i react-no-ssr

Usage:

import React from 'react';
import NoSSR from 'react-no-ssr';
import FeedComponent from './feed-component';
 
const SomePage = () => (
  <div>
    <h1>My Personalized Feed</h1>
    <hr />
    <NoSSR>
      <FeedComponent />
    </NoSSR>
  </div>
);

export default SomePage;

Which of these two methods would you choose? Both are concise and effective. Please let us know your thoughts by leaving comments. Happy coding!