---
url: /strapi-typed-client/reference/media-file.md
---
# Media & Blocks

This page documents the `MediaFile` and `BlocksContent` types generated for Strapi media attributes and the Blocks rich text editor.

## MediaFile

The `MediaFile` interface is generated for all Strapi media attributes. It represents a single uploaded file with its metadata.

```ts
export interface MediaFormat {
    ext: string
    url: string
    hash: string
    mime: string
    name: string
    path: string | null
    size: number
    width: number
    height: number
    sizeInBytes: number
}

export interface MediaFile {
    id: number
    name: string
    alternativeText: string | null
    caption: string | null
    focalPoint: { x: number; y: number } | null
    width: number | null
    height: number | null
    formats: Record<string, MediaFormat> | null
    hash: string
    ext: string
    mime: string
    size: number
    url: string
    previewUrl: string | null
    provider: string
    createdAt: string
    updatedAt: string
}
```

### Field Reference

| Field             | Type                                  | Description                                                                    |
| ----------------- | ------------------------------------- | ------------------------------------------------------------------------------ |
| `id`              | `number`                              | Database ID of the media entry                                                 |
| `name`            | `string`                              | Original file name                                                             |
| `alternativeText` | `string \| null`                      | Alt text for accessibility                                                     |
| `caption`         | `string \| null`                      | Optional caption                                                               |
| `focalPoint`      | `{ x: number; y: number } \| null`    | Upload focal point used for smart image positioning                            |
| `width`           | `number \| null`                      | Image width in pixels (null for non-images)                                    |
| `height`          | `number \| null`                      | Image height in pixels (null for non-images)                                   |
| `formats`         | `Record<string, MediaFormat> \| null` | Responsive image formats generated by Strapi (thumbnail, small, medium, large) |
| `hash`            | `string`                              | Unique hash of the file                                                        |
| `ext`             | `string`                              | File extension (e.g., `.jpg`, `.pdf`)                                          |
| `mime`            | `string`                              | MIME type (e.g., `image/jpeg`, `application/pdf`)                              |
| `size`            | `number`                              | File size in kilobytes                                                         |
| `url`             | `string`                              | URL to access the file                                                         |
| `previewUrl`      | `string \| null`                      | Preview URL (used by some providers)                                           |
| `provider`        | `string`                              | Storage provider (e.g., `local`, `aws-s3`, `cloudinary`)                       |
| `createdAt`       | `string`                              | ISO datetime of upload                                                         |
| `updatedAt`       | `string`                              | ISO datetime of last update                                                    |

### Single vs. Multiple Media

Strapi media attributes can be configured as single or multiple:

| Configuration               | Base Type           | Input Type        |
| --------------------------- | ------------------- | ----------------- |
| Single media (required)     | `MediaFile`         | `MediaInput`      |
| Single media (not required) | `MediaFile \| null` | `MediaInput`      |
| Multiple media              | `MediaFile[]`       | `MultiMediaInput` |

Where `MediaInput` is `StrapiID | null` and `MultiMediaInput` is `StrapiID[] | null` (`StrapiID = string | number`).

### Using Media with Populate

Media fields require `populate` to be included in the response. Without populate, media fields are not present on the returned type.

```ts
// Without populate — no media fields in the type
const article = await strapi.articles.findOne('abc123')
// article.cover  <-- does not exist on type

// With populate — media fields are included
const article = await strapi.articles.findOne('abc123', {
    populate: { cover: true },
})
// article.cover?.url  <-- fully typed as MediaFile | null
```

You can also select specific media fields:

```ts
const article = await strapi.articles.findOne('abc123', {
    populate: {
        cover: { fields: ['url', 'alternativeText', 'width', 'height'] },
    },
})
```

### Accessing Image URLs and Formats

```ts
const article = await strapi.articles.findOne('abc123', {
    populate: { cover: true },
})

if (article.cover) {
    // Direct URL
    const imageUrl = article.cover.url

    // Alt text for <img> tag
    const alt = article.cover.alternativeText ?? ''

    // Dimensions
    const { width, height } = article.cover

    // Responsive formats (thumbnail, small, medium, large) — fully typed
    if (article.cover.formats?.thumbnail) {
        const thumbnailUrl = article.cover.formats.thumbnail.url
        const { width, height } = article.cover.formats.thumbnail
    }
}
```

::: tip
The `formats` field is typed as `Record<string, MediaFormat> | null`, covering Strapi's default formats (thumbnail, small, medium, large) and any custom sizes you configure.
:::

### Media in Input Types

When creating or updating entries, media fields accept the file's numeric id (not file objects) — single media is typed `MediaInput`, multi media `MultiMediaInput`. Upload the file first via Strapi's upload API, then reference it by id.

```ts
// Create with media by id
await strapi.articles.create({
    title: 'New Article',
    cover: 42, // single media -> MediaInput
    gallery: [42, 43], // multiple media -> MultiMediaInput
})

// Clear a media field
await strapi.articles.update('abc123', {
    cover: null,
})
```

## Upload API

Strapi v5 ships with a built-in upload plugin. The client exposes it via `client.upload`, fully typed and using the same auth pipeline, baseURL, error handling, and Next.js cache integration as the rest of the client.

### Methods

| Method             | Endpoint                       | Returns       |
| ------------------ | ------------------------------ | ------------- |
| `upload(formData)` | `POST /api/upload`             | `MediaFile[]` |
| `find(params?)`    | `GET /api/upload/files`        | `MediaFile[]` |
| `findOne(id)`      | `GET /api/upload/files/:id`    | `MediaFile`   |
| `destroy(id)`      | `DELETE /api/upload/files/:id` | `MediaFile`   |

### Uploading files

Construct a `FormData` with the field name `files` (the Strapi convention) and pass it to `upload()`:

```ts
// Web
const input = document.querySelector<HTMLInputElement>('#picker')!
const formData = new FormData()
for (const file of input.files ?? []) {
    formData.append('files', file)
}
const uploaded = await client.upload.upload(formData)
// uploaded is MediaFile[]
```

```ts
// React Native
const formData = new FormData()
formData.append('files', {
    uri: localUri,
    name: 'photo.jpg',
    type: 'image/jpeg',
} as any)
const [file] = await client.upload.upload(formData)
```

You can also attach uploaded files directly to an existing entry by adding the standard Strapi fields to the same FormData:

```ts
formData.append('ref', 'api::article.article')
formData.append('refId', String(articleId))
formData.append('field', 'cover')
await client.upload.upload(formData)
```

### Listing files

`find()` accepts an `UploadQueryParams` shape with `filters`, `sort`, `fields`, and **flat `start`/`limit`** for pagination:

```ts
const files = await client.upload.find({
    sort: 'createdAt:desc',
    limit: 20,
    start: 0,
    filters: { mime: { $contains: 'image/' } },
})
```

::: warning Pagination quirk
The upload plugin pre-dates Strapi v5's document model and **uses flat `start`/`limit` instead of `pagination[page]`/`pagination[pageSize]`**. The `UploadQueryParams` type reflects this — TypeScript will not let you pass `pagination` here. If you copy a snippet from a collection endpoint, you'll need to convert it.
:::

::: warning Response shape
Unlike collection endpoints, the upload plugin returns a flat array — there is no `{ data, meta }` envelope. `client.upload.find()` resolves to `MediaFile[]` directly.
:::

### Reading and deleting a single file

```ts
const file = await client.upload.findOne(42)
console.log(file.url)

const deleted = await client.upload.delete(42)
// `deleted` is the MediaFile that was just removed
```

::: warning Renamed in v2
`client.upload.destroy()` is now `client.upload.delete()`. The old name remains as a `@deprecated` alias and will be removed in a future major.
:::

::: warning Numeric ids
Files use a numeric `id`, not a `documentId` — this is a quirk of the upload plugin (it pre-dates Strapi's document model). Do not pass strings:

```ts
client.upload.findOne(42) // ✅ number
client.upload.findOne('42') // ❌ type error
```

:::

### Error handling

Upload methods throw the same `StrapiError` / `StrapiConnectionError` as the rest of the client. Auth (Bearer token), timeout, and Next.js cache options are all inherited.

```ts
try {
    await client.upload.delete(42)
} catch (err) {
    if (err instanceof StrapiError && err.status === 403) {
        // missing permission to delete uploads
    }
    throw err
}
```

## BlocksContent

The `BlocksContent` type represents content from Strapi's Blocks rich text editor (the v2 rich text field introduced in Strapi v5). It is a structured array of block objects.

```ts
export type BlocksContent = Block[]
```

### Block Types

```ts
export type Block =
    | ParagraphBlock
    | HeadingBlock
    | QuoteBlock
    | CodeBlock
    | ListBlock
    | ImageBlock
```

#### ParagraphBlock

```ts
export interface ParagraphBlock {
    type: 'paragraph'
    children: InlineNode[]
}
```

#### HeadingBlock

```ts
export interface HeadingBlock {
    type: 'heading'
    level: 1 | 2 | 3 | 4 | 5 | 6
    children: InlineNode[]
}
```

#### QuoteBlock

```ts
export interface QuoteBlock {
    type: 'quote'
    children: InlineNode[]
}
```

#### CodeBlock

```ts
export interface CodeBlock {
    type: 'code'
    language?: string
    children: InlineNode[]
}
```

#### ListBlock

```ts
export interface ListBlock {
    type: 'list'
    format: 'ordered' | 'unordered'
    children: ListItemBlock[]
}

export interface ListItemBlock {
    type: 'list-item'
    children: InlineNode[]
}
```

#### ImageBlock

```ts
export interface ImageBlock {
    type: 'image'
    image: {
        name: string
        alternativeText?: string | null
        url: string
        caption?: string | null
        width?: number
        height?: number
        formats?: Record<string, MediaFormat> | null
        hash: string
        ext: string
        mime: string
        size: number
        previewUrl?: string | null
        provider: string
        createdAt: string
        updatedAt: string
    }
    children: InlineNode[]
}
```

### Inline Nodes

All block types contain `children` arrays of inline nodes:

```ts
export type InlineNode = TextNode | LinkInline
```

#### TextNode

```ts
export interface TextNode {
    type: 'text'
    text: string
    bold?: boolean
    italic?: boolean
    underline?: boolean
    strikethrough?: boolean
    code?: boolean
}
```

#### LinkInline

```ts
export interface LinkInline {
    type: 'link'
    url: string
    children: TextNode[]
}
```

### Rendering Blocks on the Frontend

`BlocksContent` is a structured data format. You need a renderer to convert it to HTML or React elements. Strapi provides an official renderer for React:

```bash
npm install @strapi/blocks-react-renderer
```

```tsx
import { BlocksRenderer } from '@strapi/blocks-react-renderer'
import type { BlocksContent } from '@/strapi'

function ArticleBody({ content }: { content: BlocksContent }) {
    return <BlocksRenderer content={content} />
}
```

::: info
The `BlocksContent` type is only generated when your schema contains at least one `blocks` type attribute. If your Strapi project uses only the classic `richtext` (Markdown) type, that field is typed as `string` instead.
:::

### Blocks vs. RichText

| Attribute Type           | Generated TypeScript Type | Format                |
| ------------------------ | ------------------------- | --------------------- |
| `richtext` (Markdown)    | `string`                  | Raw Markdown string   |
| `blocks` (Blocks editor) | `BlocksContent`           | Structured JSON array |

The `blocks` type provides a structured, renderable format, while `richtext` is a plain Markdown string that you parse and render yourself.
