# Server-Side Rendering

Server-Side Rendering (SSR) involves rendering the HTML content of a webpage-side and then sending the fully-rendered page to the browser. The browser only needs to display the page without additional rendering.

The main advantages are:

- **Improved First-Page Load Speed**: SSR generates a complete webpage on the server-side. The browser only needs to download the page content, avoiding additional rendering, thus improving the first-page load speed.
- **SEO-Friendly**: SSR can generate complete HTML content that search engines can directly index, thereby improving the website's ranking.

Developers might consider using SSR to render pages in the following scenarios:

1. Websites that require high first-page load speed, such as e-commerce and news websites.
2. Websites demanding high user experience, such as social networks and gaming websites.
3. Websites with high SEO requirements, such as company websites and blogs.

In Modern.js, SSR is also available out of the box. Developers don't need to write complex server-side logic or worry about SSR maintenance or creating separate services.

Apart from the out-of-the-box SSR service, Modern.js also offers:

- Comprehensive SSR fallback strategies to ensure the page can run safely.
- Automatic segmentation of sub-routes with on-demand loading, reducing first-page resource size.
- Built-in caching system to address high server load issues.

## Enabling SSR

Enabling SSR in Modern.js is straightforward. Simply set [`server.ssr`](/configure/app/server/ssr) to `true`:

```ts title="modern.config.ts"
import { defineConfig } from '@modern-js/app-tools';

export default defineConfig({
  server: {
    ssr: true,
  },
});
```

## Data Fetching

:::tip Prerequisite
If you're unfamiliar with how to use Data Loader or the concept of Client Loader, please read [Data Fetching](/guides/basic-features/data/data-fetch) first.
:::

### Basic Usage

Modern.js provides Data Loader, enabling developers to fetch data isomorphically under both SSR and CSR. Each route module, such as `layout.tsx` and `page.tsx`, can define its own Data Loader:

```ts title="src/routes/page.data.ts"
export const loader = () => {
  return {
    message: 'Hello World',
  };
};
```

In components, you can use hook APIs to access the data returned by the `loader` function:

```tsx
import { useLoaderData } from '@modern-js/runtime/router';
export default () => {
  const data = useLoaderData();
  return <div>{data.message}</div>;
};
```

### Using Client Loader

:::info
This feature requires version x.36.0 or above. We recommend using the latest version of the framework.
:::

By default, in SSR applications, the `loader` function only executes on the server. However, in some scenarios, developers might want requests made on the client-side to bypass the SSR service and directly fetch data from the source. For example:

1. Reducing network consumption on the client-side by directly fetching from the data source.
2. The application has data cached on the client side and doesn't want to fetch data from the SSR service.

Modern.js supports adding a `.data.client` file, also named exported as `loader`, in SSR applications. If the Data Loader fails to execute on the server side, or when navigating on the client side, it will execute the `loader` function on the client side instead of sending a data request to the SSR service.

```ts title="page.data.client.ts"
import cache from 'my-cache';

export async function loader({ params }) {
  if (cache.has(params.id)) {
    return cache.get(params.id);
  }
  const res = await fetch('URL_ADDRESS?id={params.id}');
  return {
    message: res.message,
  }
}
```

:::warning
To use Client Loader, there must be a corresponding Server Loader, and the Server Loader must be in a `.data` file, not a `.loader` file.
:::

## SSR Fallback

In Modern.js, if an application encounters an error during SSR, it automatically falls back to CSR mode and re-fetches data, ensuring the page can display correctly. SSR fallback can occur for two main reasons:

1. Data Loader execution error.
2. React component rendering error on the server side.

### Data Loader Execution Error

By default, if the `loader` function for a route throws an error, the framework renders the `<ErrorBoundary>` component directly on the server, displaying the error message. This is the default behavior of most frameworks.

Modern.js also supports customizing the fallback strategy through the `loaderFailureMode` field in the [`server.ssr`](/configure/app/server/ssr) configuration. Setting this field to `clientRender` immediately falls back to CSR mode and re-fetches the data.

If a Client Loader is defined for the route, it will be used to re-fetch the data. If re-rendering fails again, the `<ErrorBoundary>` component will be displayed.

{/* Todo Add a diagram */}

### Component Rendering Error

If the Data Loader executes correctly but the component rendering fails, SSR rendering will partially or completely fail, as shown in the following code:

```tsx
import { Await, useLoaderData } from '@modern-js/runtime/router';
import { Suspense } from 'react';

const Page = () => {
  const data = useLoaderData();
  const isNode = typeof window === 'undefined';
  const undefinedVars = data.unDefined;
  const definedVars = data.defined;

  return (
    <div>
      {isNode ? undefinedVars.msg : definedVars.msg}
    </div>
  );
};

export default Page;
```

In this case, Modern.js will fallback the page to CSR and use the existing data from the Data Loader to render. If the rendering still fails, the `<ErrorBoundary>` component will be rendered.

:::tip
The behavior of component rendering errors is unaffected by `loaderFailureMode` and will not execute the Client Loader on the browser side.
:::

{/* Todo Add a diagram */}

## Logging and Monitoring

import Monitor from '@site-docs-en/components/ssr-monitor';

<Monitor />

## Page Caching

Modern.js has built-in caching capabilities. Refer to [Rendering Cache](/guides/basic-features/render/ssr-cache) for details.

## Differences in Runtime Environment

SSR applications run on both the server and the client, with differing Web and Node APIs.

When enabling SSR, Modern.js uses the same entry to build both SSR and CSR bundles. Therefore, having Web APIs in the SSR bundle or Node APIs in the CSR bundle can lead to runtime errors. This usually happens in two scenarios:

- There are issues in the application's own code.
- The dependency package contains side effects.

### Issues with Own Code

This scenario often arises when migrating from CSR to SSR. CSR applications typically import Web APIs in the code. For example, an application might set up global event listeners:

```tsx
document.addEventListener('load', () => {
  console.log('document load');
});
const App = () => {
  return <div>Hello World</div>;
};
export default App;
```

In such cases, you can use Modern.js built-in environment variables `MODERN_TARGET` to remove unused code during the build:

```ts
if (process.env.MODERN_TARGET === 'browser') {
  document.addEventListener('load', () => {
    console.log('document load');
  });
}
```

After packing in the development environment, the SSR and CSR bundles will compile as follows. Therefore, Web API errors will not occur in the SSR environment:

```ts
// SSR Bundle
if (false) {
}

// CSR Bundle
if (true) {
  document.addEventListener('load', () => {
    console.log('document load');
  });
}
```

:::note
For more information, see [Environment Variables](/guides/basic-features/env-vars).
:::

### Side Effects in Dependencies

This scenario can occur at any time in SSR applications because not all community packages support running in both environments. Some packages only need to run in one. For instance, importing package A that has a side effect using Web APIs:

```ts title="packageA"
document.addEventListener('load', () => {
  console.log('document load');
});

export const doSomething = () => {}
```

Directly referencing this in a component will cause CSR to throw errors, even if you use environment variables to conditionally load the code. The side effects in the dependency will still execute.

```tsx title="routes/page.tsx"
import { doSomething } from 'packageA';

export const Page = () => {
  if (process.env.MODERN_TARGET === 'browser') {
    doSomething();
  }
  return <div>Hello World</div>
}
```

Modern.js supports distinguishing between SSR and CSR bundles by using `.server.` suffix files. You can create `.ts` and `.server.ts` files with the same name to create a proxy:

```ts title="a.ts"
export { doSomething } from 'packageA';
```

```ts title="a.server.ts"
export const doSomething: any = () => {};
```

Import `./a` in the file, and the SSR bundle will prioritize the `.server.ts` files, while the CSR bundle will prioritize the `.ts` files.

```tsx title="routes/page.tsx"
import { doSomething } from './a'

export const Page = () => {
  doSomething();
  return <div>Hello World</div>
}
```

## Common Issues

### Ensuring Consistent Rendering

In SSR applications, it is crucial to ensure that the rendering results on the server are consistent with the hydration results in the browser. Inconsistent rendering may lead to unexpected outcomes. Here’s an example demonstrating issues when SSR and CSR render differently. Add the following code to your component:

```tsx
{
  typeof window !== 'undefined' ? <div>browser content</div> : null;
}
```

After starting the application and visiting the page, you will notice a warning in the browser console:

```sh
Warning: Expected server HTML to contain a matching <div> in <div>.
```

This warning is caused by a mismatch between the React hydrate results and the SSR rendering results. Although the current page appears normal, complex applications may experience DOM hierarchy disruptions or style issues.

:::info
For more information on React hydrate logic, refer to [here](https://zh-hans.react.dev/reference/react-dom/hydrate).
:::

The application needs to maintain consistency between SSR and CSR rendering results. If inconsistencies occur, it indicates that some content should not be rendered by SSR. Modern.js provides the `<NoSSR>` utility component for such scenarios:

```ts
import { NoSSR } from '@modern-js/runtime/ssr';
```

Wrap elements that should not be server-side rendered with the `NoSSR` component:

```tsx
<NoSSR>
  <div>browser content</div>
</NoSSR>
```

After modifying the code, refresh the page and notice that the previous warning has disappeared. Open the browser's developer tools and check the Network tab. The returned HTML document will not contain the content wrapped by the `NoSSR` component.

In practical scenarios, some UI displays might be affected by the user's device, such as [UA](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/User-Agent) information. Modern.js also provides APIs like [`useRuntimeContext`](/apis/app/runtime/core/use-runtime-context), allowing components to access complete request information and maintaining SSR and CSR rendering consistency.

### Attention to Memory Leaks

:::warning Alert
In SSR scenarios, developers need to pay special attention to memory leaks. Even minor memory leaks can significantly impact services after many requests.
:::

With SSR, each browser request triggers server-side component rendering. Therefore, you should avoid defining any data structures that continually grow globally, subscribing to global events, or creating non-disposable streams.

For example, when using [redux-observable](https://redux-observable.js.org/), developers accustomed to CSR might code as follows:

```tsx
/* Code is just an example and not executable */
import { createEpicMiddleware, combineEpics } from 'redux-observable';

const epicMiddleware = createEpicMiddleware();
const rootEpic = combineEpics();

export default function Test() {
  epicMiddleware.run(rootEpic);
  return <div>Hello Modern.js</div>;
}
```

In this case, the `epicMiddleware` instance is created outside the component, and `epicMiddleware.run` is called within the component.

This code does not cause issues on the client-side. However, in SSR, the Middleware instance remains non-disposable. Each time the component renders, calling `epicMiddleware.run(rootEpic)` adds new event bindings internally, causing the entire object to grow continuously, ultimately affecting application performance.

Such issues are not easily noticed in CSR. When transitioning from CSR to SSR, if you're unsure whether your application has such hidden pitfalls, consider stress testing the application.