import { Meta } from '@storybook/addon-docs/blocks';

<Meta title="Guides/Installation/SSR/Next.js app router" />

# Installation: Next.js app router

This guide assumes you have read and followed the steps in the [Installation: Applications](/story/guides-installation-applications--page) guide.

## Packages

You will need to install one extra package. `@preply/ds-web-core`, which provides you with everything you need to collect stylesheets and CSS classes during SSR time.

```
yarn add @preply/ds-web-core
```

## Create a client component for collecting styles and rendering provider

```tsx
'use client';

import { ReactNode, useState } from 'react';
import { RootProvider, SSRProvider } from '@preply/ds-web-root';
import { ServerStyleSheet } from '@preply/ds-web-core';
import { useServerInsertedHTML } from 'next/navigation';

const hostname = process.env.PREPLY_HOST; // or any other way to get the hostname

export const DSProvider = ({ children }: { children: ReactNode }) => {
    const [stylesheet] = useState(() => new ServerStyleSheet());

    useServerInsertedHTML(() => {
        const styles = stylesheet.getStyleElement();
        return <>{styles}</>;
    });

    return (
        <SSRProvider stylesheet={stylesheet} hostname={hostname}>
            <RootProvider theme="tokyo-ui" target="none">
                {children}
            </RootProvider>
        </SSRProvider>
    );
};
```

## Add DSProvider and the global styles to the root layout.tsx

```tsx
import type { Metadata } from 'next';
import { DSProvider } from '../components/DSProvider';
import { GlobalStyle } from '@preply/ds-web-root';

export const metadata: Metadata = {
    title: 'Create Next App',
    description: 'Generated by create next app',
};

export default function RootLayout({ children }: { children: React.ReactNode }) {
    return (
        <html lang="en">
            <head>
                <link rel="preconnect" href="https://static.preply.com" />
                <GlobalStyle />
            </head>
            <body>
                <DSProvider>{children}</DSProvider>
            </body>
        </html>
    );
}
```

See also [Next.js official docs](https://nextjs.org/docs/app/building-your-application/styling/css-in-js).
