# SSR & Next.js

> What renders on the server, who owns the controller, and complete setups for Next.js and Vite.

Source: https://cloudlet.dev/docs/components/toaster/ssr

## What renders on the server

Nothing. The Toaster's server output is empty, and so is its first render during hydration, even with notifications already accepted, so it never causes a hydration mismatch. Notifications you `show` before it mounts wait in the controller.

The notification center renders nothing on the server either: [SSR and Next.js](https://cloudlet.dev/docs/components/notification-center#ssr-and-nextjs) on its page.

The package keeps the `"use client"` directive on its React entry, so importing `Toaster`, `CloudletProvider` or `useCloudlet` from a Server Component file marks the boundary correctly. The controller is a live object with methods and subscriptions: it is not serializable and never crosses from a Server Component into a client one.

Your own components read the state as the Toaster does: [`getServerSnapshot()`](https://cloudlet.dev/docs/components/toaster/api/controller#getsnapshot-and-getserversnapshot) makes the server and the first client render agree, and the real state arrives right after hydration:

```tsx title="notification-count.tsx"
'use client';
import { useSyncExternalStore } from 'react';
import { useCloudlet } from '@cloudlet/toast';

/** How many notifications wait in the stack; 0 on the server and during hydration. */
export function NotificationCount() {
  const cloudlet = useCloudlet();
  const count = useSyncExternalStore(
    cloudlet.subscribe,
    () => cloudlet.getSnapshot().stack.length,
    () => cloudlet.getServerSnapshot().stack.length,
  );
  return count > 0 ? <span>{count} new</span> : null;
}
```

## One controller per session or request

A controller holds one user's notifications; never share one between users.

- **In the browser**, create it once per session: it lives as long as the page or the part of the application that owns it.
- **On the server**, a controller that takes part in rendering belongs to that request alone. A module-level controller in code that also runs on the server would be shared by every request, so server-rendered applications create the controller in the browser, in a client component ([App Router](#nextjs-app-router)).

When you render on the server yourself, create the controller inside the request and dispose it once the response is written:

```tsx title="entry-server.tsx"
import { renderToString } from 'react-dom/server';
import { CloudletProvider, createCloudlet, Toaster } from '@cloudlet/toast';

function App() {
  return <main>Weather station</main>;
}

export function render() {
  // This request's own controller: the Toaster renders nothing into the HTML.
  const cloudlet = createCloudlet();
  try {
    return renderToString(
      <CloudletProvider controller={cloudlet}>
        <App />
        <Toaster />
      </CloudletProvider>,
    );
  } finally {
    cloudlet.dispose();
  }
}
```

The browser entry then creates its own controller and hydrates the same tree.

### When to dispose

[`dispose()`](https://cloudlet.dev/docs/components/toaster/api/controller#dispose) is final. Call it only when the session the controller belongs to is over: a test that finished, a micro-frontend removed for good, a server request that has been answered. A single-page application usually never calls it; the controller lives as long as the page. Unmounting the Toaster does not end the controller ([Toaster props](https://cloudlet.dev/docs/components/toaster/api/toaster#props)): mounting a Toaster again resumes the same queue.

Never create the controller in a component body: every render would create a new controller with an empty stack. Create it in the bootstrap, or in an effect of a client owner as in the [App Router](#nextjs-app-router) setup.

## Next.js App Router

The App Router renders every page on the server first, so a client component owns the controller: its effect creates the controller, and its cleanup disposes exactly that instance. Until the controller exists, the Provider gets `null`, the Toaster renders nothing and your pages render on the server as usual.

```tsx title="components/notification-owner.tsx"
'use client';
import { useEffect, useState, type ReactNode } from 'react';
import { CloudletProvider, createCloudlet, Toaster, type ReactCloudletController } from '@cloudlet/toast';

export function NotificationOwner({ children, nonce }: { children: ReactNode; nonce?: string | undefined }) {
  const [controller, setController] = useState<ReactCloudletController | null>(null);

  useEffect(() => {
    const instance = createCloudlet();
    setController(instance);
    // Dispose this instance, not whichever controller is current.
    return () => instance.dispose();
  }, []);

  // `null` on the server and in the first client render: the Toaster waits, the children do not.
  return (
    <CloudletProvider controller={controller}>
      {children}
      {/* The request's nonce, under a strict Content Security Policy. */}
      <Toaster {...(nonce ? { nonce } : {})} />
    </CloudletProvider>
  );
}
```

`nonce` is optional: without a strict Content Security Policy leave it out; with one, [Content Security Policy](https://cloudlet.dev/docs/components/toaster/csp#nextjs-app-router) shows where the layout gets it ([`nonce`](https://cloudlet.dev/docs/components/toaster/api/toaster#props)).

The root layout imports the stylesheet once and wraps the application in the owner:

```tsx title="app/layout.tsx"
import '@cloudlet/toast/styles.css';
import type { ReactNode } from 'react';
import { NotificationOwner } from '../components/notification-owner';

export default function RootLayout({ children }: { children: ReactNode }) {
  return (
    <html lang="en">
      <body>
        <NotificationOwner>{children}</NotificationOwner>
      </body>
    </html>
  );
}
```

Client components show notifications through [`useOptionalCloudlet()`](https://cloudlet.dev/docs/components/toaster/api/toaster#useoptionalcloudlet). It is `null` before the owner's effect runs, which matters only during render: events fire after hydration, when the controller exists:

```tsx title="components/save-button.tsx"
'use client';
import { useOptionalCloudlet } from '@cloudlet/toast';

export function SaveButton() {
  const cloudlet = useOptionalCloudlet();
  return (
    <button
      disabled={!cloudlet}
      onClick={() => cloudlet?.show({ title: 'Forecast saved', kind: 'success' })}
    >
      Save forecast
    </button>
  );
}
```

Keep [`useCloudlet()`](https://cloudlet.dev/docs/components/toaster/api/toaster#usecloudlet), which throws while the controller is `null`, for components that render only after the owner has mounted, such as content of a dialog the user opens.

The shadcn registry item works a little differently: its wrapper renders the Provider and the Toaster for a controller you pass in, and the `notification-owner.tsx` of [Installation](https://cloudlet.dev/docs/components/toaster#installation) renders it once that controller exists.

### React Strict Mode

In development Strict Mode runs the owner's effect, its cleanup, and the effect again: the first controller is disposed before anything uses it, and the Toaster attaches to the second. That works because the cleanup disposes the instance its own effect created. Two variants break under the replay:

- disposing the controller from state (`controller.dispose()` in a cleanup), which disposes the instance the second setup still needs;
- creating the controller once outside the effect and disposing it in the cleanup, which leaves the remounted owner with a disposed controller.

## Next.js Pages Router

Global CSS is imported from the custom App, and the same client owner wraps every page. `_app` stays mounted across client-side navigations, so one controller serves the whole session:

```tsx title="pages/_app.tsx"
import '@cloudlet/toast/styles.css';
import type { AppProps } from 'next/app';
import { NotificationOwner } from '../components/notification-owner';

export default function App({ Component, pageProps }: AppProps) {
  return (
    <NotificationOwner>
      <Component {...pageProps} />
    </NotificationOwner>
  );
}
```

With the shadcn wrapper, its two CSS imports move into `_app` too, in the order given in [The shadcn registry item](https://cloudlet.dev/docs/components/toaster#the-shadcn-registry-item).

Both routers need a matching pair of `react` and `react-dom` in the range of [Requirements](https://cloudlet.dev/docs/components/toaster#requirements).

## Vite and other client-only apps

Without server rendering there is nothing to hydrate: create the controller once at module scope of the client entry and render the Provider and the Toaster there, as in [Usage](https://cloudlet.dev/docs/components/toaster#usage). With Vite's SSR mode, the server entry follows [One controller per session or request](#one-controller-per-session-or-request).
