Learn how to disable SSR in Next.js and use it to replace Create React App or any custom tooling.
Next.js is my absolute favorite tool for developing React applications. It offers you a best-in-class developer experience. It also has a ton of useful features for being more productive and optimizing your apps in production:
- Static & server rendering
- TypeScript support
- Multiple entry points
- Bundle-splitting and tree-shaking
However, in the past, I did not want to use it for all my React apps. Next.js does not work without server-side rendering (SSR) by default. I preferred using a non-SSR solution like Create React App, when my app did not require SSR, because SSR had caused me so many unnecessary problems.
Then, one day Tanner Linsley, the author of React Query, posted on Twitter that he was using Next.js without SSR as a replacement for Create React App:
My react CLI journey (for building @nozzleio's SPA) took one more step today:
🔽 Custom Webpack
🔽 Create React App
🔽 React Static
🔽 Create React App
🔽 Rescripts CLI
✅ Next.js + Rewrites + React Router v6
Turns out Next is still 💯/💯, even if you only need index.js!
AMA22:13 PM - 09 Sep 2020
I was stoked! After a little bit of research, I was able to do this myself. 🤯
Why Disable SSR in Next.js?
SSR for React apps is necessary in a few cases:
- The app's content needs to rank high on search results (SEO).
- You need social-media previews (Facebook, Twitter, Slack, etc.).
- You need the additional speed optimizations it can provide for your users.
However, using SSR has multiple trade-offs and challenges:
- You need a complicated hosting environment. You cannot just upload your app to a server or a CDN. You need Node.js servers doing the server-side rendering. This adds complexity and also costs more.
- You need to make sure your code works both on the browser and on the server (Node.js). This makes debugging harder and restricts you in some cases. For example, you cannot use localStorage to store authorization information, but you need to pass it in a cookie and use a cookie library that works on the server and the browser.
I've probably spent around 1-2 days in total trying to setup and debug Sentry with Next.js in Zeit Now. Without SSR (or Serverless) this would have been < 1 hour.
Serverless + React SSR != "works out-of-the-box"11:09 AM - 20 Feb 2020
-
It affects your application architecture. For example, server-side rendering needs to be done in a single render, so you need to fetch all the data for the page in a single location (like
getInitialProps
). This requirement complicates data fetching with libraries like Redux or React Query and often leads to duplicate code.
If you don't need SSR, these trade-offs are not worth it. Basically, you should consider disabling SSR for all apps where the UI is behind a login.
Heuristic: If your app is behind a login, you likely should disable SSR.
How can you disable SSR in Next.js?
Let's go through the steps for disabling SSR for a fresh Next.js application (created with npx create-next-app
).
Step 1: Rewrite All Requests to pages/index.js
Next.js supports adding redirects. Create a file named next.config.js
to the root of your project. Add the following configuration there:
module.exports = {
target: "serverless",
async rewrites() {
return [
// Rewrite everything to `pages/index`
{
source: "/:any*",
destination: "/",
},
];
},
};
These redirects work only in the development environment. In production, you need to have a proxy server like NGINX or use your hosting platform's capabilities (e.g. Netlify's redirects) for doing these redirects.
Step 2: Disable SSR for Page Content
To disable SSR for page content, we need to add the following code to pages/_app.js
:
import '../styles/globals.css'
function SafeHydrate({ children }) {
return (
<div suppressHydrationWarning>
{typeof window === 'undefined' ? null : children}
</div>
)
}
function MyApp({ Component, pageProps }) {
return <SafeHydrate><Component {...pageProps} /></SafeHydrate>
}
export default MyApp
In the code above, we wrap our page content to a component called SafeHydrate
that allows us to prevent the page content from rendering on the server. Let's go through what is happening in the code above.
With Next.js you can check if we're on the server by checking if the window
object is undefined
.
if(typeof window === 'undefined') {
// This code will only execute on the server
// and not in the browser
}
However, we cannot just wrap our code into this if
-statement directly. If you try it, you'll notice that React will produce an annoying hydration mismatch warning in the console: Warning: Expected server HTML to contain a matching <div> in <div>.
This happens, if the server HTML is different from what the browser renders.
In our case, it is safe to ignore this warning. To keep things tidy, we want to completely hide the warning from the console. This can be done by rendering a div with the prop suppressHydrationWarning
. For better readability, we create a separate SafeHydrate
component for this and wrap our page component into it.
Step 3: Check that Everything Works with npm run dev
Now, run npm run dev
in your terminal. After the server is running at http://localhost:3000/ you should able to go to any URL (like http://localhost:3000/some/random/path) and see the content of index.js there.
Success! 🎉
Step 4: Build production bundles with next export
We want to deploy our app as a static bundle that can be served without a Node.js server. For this, Next.js offers the command next export
. It will create a static version of your app in the out
directory.
To use the command, update the "build" script in your package.json
like this:
"scripts": {
...
"build": "next build && next export"
...
}
Now, run npm run build
. When you see the message Export successful
, congrats! You now have a working static Next.js app in the out
directory. 🎉
You can check the whole example app from this Github repository
Notes on Routing and other Advanced features
Routing
Next.js does not support dynamic routing if you don't have a server running. You need a router like react-router
. The setup is the same as with other tools like Create React App.
Updating the <title>
and Other <head>
Tags
You don't need to add something like react-helmet
for updating the head
, Next.js <Head />
component will work.
Having Multiple Separate Pages
If you want, you can still use Next.js pages to have multiple different pages as separate entry points for your app. This will make your bundles per route smaller and speed up your development environment because only a part of the app will be built when you make changes.
For example, if you have a page /accounts
you can create a file pages/account.js
and add a corresponding rewrite:
module.exports = {
target: "serverless",
async rewrites() {
return [
// Rewrite everything under `/account/ to `pages/account`
{
source: "/account/:any*",
destination: "/account",
},
// Rewrite everything else to `pages/index`
{
source: "/:any*",
destination: "/",
},
];
},
};
How's this different from using Next.js getStaticProps
with getStaticPaths
?
Using getStaticProps
with getStaticPaths
allows you to do Static Site Generation (SSG). This means that all the pages in your app are generated as individual .html
-files when you run npm run build
.
SSG is awesome, but has a single big limitation: You need to know all the paths your app has ahead of time. This is not possible with many apps that have tons of user-specific paths like /my-payments/123121521241
.
With the approach described in this article, you can use a dynamic router like react-router
with Next.js just like you would with Create React App or any traditional single-page app.