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

Last updated on June 12, 2021 A Goodman Loading... Post a comment

There may be cases 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.

Using dynamic() function

What wee 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 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 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;

Conclusion

You’ve learned 2 techniques to prevent some specific pages from server-side rendering in Next.js. If you’d like to explore more new and interest things about frontend development, take a look at the following articles:

You can also check our React topic page and Next.js topic page for the latest tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Related Articles