# fetchContent

Learn how to fetch content using a standalone function.

This method fetches the content of a slot on the server side.

## Signature

This function has the following signature:

```ts
fetchContent<T extends SlotId>(id: T, options: FetchOptions): Promise<FetchResponse<T>>
```

## Example

Here is a minimal example of how to use this function:

**Basic example**

**App router — JavaScript**

```jsx
import {fetchContent} from '@croct/plug-next/server';

export async function HomeHero() {
  const {content} = await fetchContent('home-hero');

  return (
    <div>
      <strong>{content.title}</strong>
      <p>{content.subtitle}</p>
      <a href={content.button.link}>{content.button.label}</a>
    </div>
  );
}
```

**App router — TypeScript**

```tsx
import type {ReactElement} from 'react';
import {fetchContent} from '@croct/plug-next/server';

export async function HomeHero(): Promise<ReactElement> {
  const {content} = await fetchContent('home-hero');

  return (
    <div>
      <strong>{content.title}</strong>
      <p>{content.subtitle}</p>
      <a href={content.button.link}>{content.button.label}</a>
    </div>
  );
}
```

**Page router — JavaScript**

**pages/index.jsx**

```jsx
import {fetchContent} from '@croct/plug-next/server';
import {HomeHero} from '../components/HomeHero';

export const getServerSideProps = async context => ({
  props: await fetchContent('home-hero', {route: context})
});

export default function HomePage({content}) {
  return (
    <div>
      <HomeHero {...content} />
    </div>
  );
}
```

**components/HomeHero.jsx**

```js
export function HomeHero(props) {
  return (
    <div>
      <strong>{props.title}</strong>
      <p>{props.subtitle}</p>
      <a href={props.button.link}>{props.button.label}</a>
    </div>
  );
}
```

**Page router — TypeScript**

**pages/index.tsx**

```tsx
import type {ReactElement} from 'react';
import {fetchContent} from '@croct/plug-next/server';
import type {GetServerSideProps} from 'next';
import {HomeHero, HomeHeroProps} from '../components/HomeHero';

type HomePageProps = {
  content: HomeHeroProps
}

export const getServerSideProps: GetServerSideProps<HomePageProps> = async context => ({
  props: await fetchContent('home-hero', {route: context})
});

export default function HomePage({content}: HomePageProps): ReactElement {
  return (
    <div>
      <HomeHero {...content} />
    </div>
  );
}
```

**components/HomeHero.tsx**

```tsx
import type {ReactElement} from 'react';

export type HomeHeroProps = {
  title: string;
  subtitle: string;
  button: {
    label: string;
    link: string;
  };
};

export function HomeHero(props: HomeHeroProps): ReactElement {
  return (
    <div>
      <strong>{props.title}</strong>
      <p>{props.subtitle}</p>
      <a href={props.button.link}>{props.button.label}</a>
    </div>
  );
}
```

For more examples, see the [Content rendering](/reference/sdk/nextjs/content-rendering).

## Parameters

The following list describes the supported parameters:

- `id`: `string`

  The ID of the slot to fetch.

  You can specify the version of the slot by passing a versioned ID in the form `id@version`. For example, passing `home-hero@1` will fetch the content for the `home-hero` slot in version 1. Not specifying a version number is the same as passing `home-hero@latest`, which will load the content for the latest version.

  > **Best practice**
  >
  > Always specify a version to ensure the front end receives content with the expected structure despite future schema changes.
  >
  > For more information, see [Slot versioning](/explanation/slot#versioning).

- `options`: `object`

  The evaluation options.

  - `route`: `object` (optional)

    The context of the current route.

    > **Conditional requirement**
    >
    > This option is only needed for [Page router](https://nextjs.org/docs/pages) or [API routes](https://nextjs.org/docs/pages/building-your-application/routing/api-routes), as the current request scope is only accessible through the [App router](https://nextjs.org/docs/app) and [Server actions](https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions-and-mutations).

    The property names are aligned with those in Next.js for easy forwarding, as shown in the [Page router example](#example).

    - `req`: `NextApiRequest|NextRequest|GetServerSidePropsRequest`

      The request object.

    - `res`: `NextApiResponse|NextResponse|GetServerSidePropsResponse`

      The response object.

  - `clientId`: `string` (optional)

    The ID of the client (browser), in the form of a UUID.

    > **Auto-configuration**
    >
    > The SDK automatically generates and forwards the client ID from the incoming request, so you do not need to specify this option unless you want to override it.

    This must be a persistent identifier that uniquely identifies the user across sessions.

    Note that specifying this option when requesting [static content](#options-static-prop) has no effect.

  - `clientAgent`: `string` (optional)

    The user agent of the client (browser).

    > **Auto-configuration**
    >
    > The SDK automatically forwards the user agent from the incoming request, so you do not need to specify this option unless you want to override it.

    If not specified or unknown, [device technology information](/reference/cql/context#technology) will be limited or unavailable.

    Note that specifying this option when requesting [static content](#options-static-prop) has no effect.

  - `clientIp`: `string` (optional)

    The IP address of the client (end-user).

    > **Auto-configuration**
    >
    > The SDK automatically forwards the IP address from the incoming request, so you do not need to specify this option unless you want to override it.

    Passing `127.0.0.1` makes the API uses IP address of the incoming request, which is useful for local development.

    If not specified or unknown, [geographic location information](/reference/cql/context#location) will be limited or unavailable.

    Note that specifying this option when requesting [static content](#options-static-prop) has no effect.

  - `static`: `boolean` (optional) (default: false)

    Whether to fetch static content.

    By default, the SDK fetches dynamic content. Set this option to `true` to fetch the slot's default static content instead.

  - `preferredLocale`: `string` (optional) (default: default locale)

    The locale code to fetch the content.

    > **Auto-configuration**
    >
    > The SDK auto-detects the preferred locale if you are using [Internationalized Routing](https://nextjs.org/docs/advanced-features/i18n-routing), so you do not need to specify this option unless you want to override it.

    The code consists of a two-part string that specifies the language and, optionally, the country. For example, `en` represents English, `en-us` stands for English (United States), and `pt-br` for Portuguese (Brazil). It is case-insensitive and supports both hyphens and underscores as separators to accommodate the different conventions used by browsers, libraries, and other systems.

    If no content is available in the preferred locale, the default locale content is returned instead.

  - `userToken`: `string` (optional)

    A base64-encoded [JSON Web Token (JWT)](https://jwt.io) that identifies the user.

    > **Auto-configuration**
    >
    > The SDK automatically generates and sets the token, so you do not need to specify this option unless you want to override it.

    If the **Require signed token** option is enabled in the [Application settings](https://app.croct.com/redirect/organizations/-organization-/workspaces/-workspace-/applications/-application-/settings), a signed JWT is required. In this case, the [token must be signed](/explanation/application/signed-tokens) using an [API key](/explanation/application/api-keys) with **Issue user tokens** permission, or the request will fail with an authorization error.

  - `previewToken`: `string` (optional)

    A base64-encoded [JSON Web Token (JWT)](https://jwt.io) that identifies the preview session.

    > **Auto-configuration**
    >
    > The SDK auto-detects the preview token from the incoming request, so you do not need to specify this option unless you want to override it.

    When previewing content, the platform generates a preview token and passes it to your application as a URL parameter. This token must be forwarded through this option to enable preview mode.

  - `includeSchema`: `boolean` (optional) (default: )

    Whether to include the [content schema](/reference/content/schema/introduction) in the response [metadata](/reference/api/service/content/endpoint/client/content#metadata-prop).

  - `timeout`: `number` (optional)

    The maximum fetch time in milliseconds.

    > **Environment variable**
    >
    > You can also set this option by defining the environment variable [`NEXT_PUBLIC_CROCT_DEFAULT_FETCH_TIMEOUT`](../environment-variables#next_public_croct_default_fetch_timeout-prop).

    Once reached, the SDK will abort the request and reject the promise with a timeout error.

  - `baseEndpointUrl`: `string` (optional)

    The base URL to use for the API calls.

    > **Environment variable**
    >
    > You can also set this option by defining the environment variable [`NEXT_PUBLIC_CROCT_BASE_ENDPOINT_URL`](../environment-variables#next_public_croct_base_endpoint_url-prop).

    By default, the SDK uses the production endpoint. This option is helpful for testing purposes and allows you to point the SDK to another environment, such as a [mock server](../../testing/integration-testing#create-a-mock-server).

    These are the endpoints that use the base URL:

    | Path                           | Description                                            |
    | ------------------------------ | ------------------------------------------------------ |
    | `/client/web/content`          | Endpoint for client-side retrieval of dynamic content. |
    | `/external/web/content`        | Endpoint for server-side retrieval of dynamic content. |
    | `/client/web/static-content`   | Endpoint for client-side retrieval of static content.  |
    | `/external/web/static-content` | Endpoint for server-side retrieval of static content.  |

    See [Integration tests](../../testing/integration-testing) for more information on how to mock the API calls.

  - `extra`: `object` (optional)

    Additional options to pass to the [`fetch`](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch) function.

  - `logger`: `object` (optional)

    A custom logger to handle log messages.

    By default, warnings and errors are logged to the console, and everything else is suppressed.

    - `debug`: `(message: string) => void`

      A function to log debug messages.

    - `info`: `(message: string) => void`

      A function to log informational messages.

    - `warn`: `(message: string) => void`

      A function to log warning messages.

    - `error`: `(message: string) => void`

      A function to log error messages.

  - `context`: `object` (optional)

    Information about the user context, such as the time zone, campaign, and page.

    - `timeZone`: `string` (optional)

      The time zone of the user, represented by an [IANA time zone ID](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones#list), like `America/New_York`.

      This information is used for time-based features like localization and scheduling, and usually comes from the browser's preferences or the user's profile.

    - `campaign`: `object` (optional)

      Information about the marketing campaign that brought the user to the page.

      > **Auto-configuration**
      >
      > The SDK automatically forwards this information from the incoming request, so you do not need to specify this option unless you want to override it.

      For more information on how to use this information, see [Marketing variables](/reference/cql/context#marketing);

      - `name`: `string` (optional)

        The name of the campaign, such as `summer-sale`.

        This information usually comes from the `utm_campaign` URL parameter.

      - `source`: `string` (optional)

        The source of the campaign, such as `google`.

        This information usually comes from the `utm_source` URL parameter.

      - `medium`: `string` (optional)

        The medium of the campaign, such as `cpc`.

        This information usually comes from the `utm_medium` URL parameter.

      - `term`: `string` (optional)

        The term of the campaign, such as `running shoes`.

        This information usually comes from the `utm_term` URL parameter.

      - `content`: `string` (optional)

        The content of the campaign, such as `banner ad`.

        This information usually comes from the `utm_content` URL parameter.

    - `page`: `object` (optional)

      Information about the page the user is currently viewing.

      > **Auto-configuration**
      >
      > The SDK automatically forwards this information from the incoming request, so you do not need to specify this option unless you want to override it.

      For more information on how to use this information, see [Navigation variables](/reference/cql/context#navigation).

      - `url`: `string`

        The URL of the page, such as `https://www.example.com/products`.

        This information usually comes from the [`window.location.href`](https://developer.mozilla.org/en-US/docs/Web/API/Location/href) property.

      - `title`: `string` (optional)

        The title of the page, such as `Products`.

        This information usually comes from the [`document.title`](https://developer.mozilla.org/en-US/docs/Web/API/Document/title) property.

      - `referrer`: `string` (optional)

        The URL of the page that linked to the current page, such as `https://www.google.com`.

        This information usually comes from the [`Referer`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referer) HTTP header or the [`document.referrer`](https://developer.mozilla.org/en-US/docs/Web/API/Document/referrer); property.

    - `attributes`: `object` (optional)

      The map of attributes to inject in the evaluation context.

      The attributes can be referenced in audience conditions using the [`context`](/reference/cql/context#evaluation) variable. For example, suppose you pass the following attributes:

      ```json
      {cities: ["New York", "San Francisco"]}
      ```

      You can then reference them in queries like:

      ```cql
      context's cities include location's cityName
      ```

      For more information, see [Context variables](../../content-rendering#context-variables).

      The following restrictions apply to the attributes:

      - Up to 30 entries and 5 levels deep
      - Keys can be either numbers or non-empty strings with a maximum length of 50 characters
      - Values can be null, numbers, booleans, strings (up to 50 characters), or nested maps
      - Nested maps follow the same constraints for keys and values
