# Images

Image sizing, placeholders and optimization.

Images load lazily, and Vuesho reads their width and height when the site builds, so the layout doesn't shift while they load. On a host with an image optimizer, the browser gets each image at the width the screen needs.

## Image Paths [#image-paths]

An image path takes one of three forms:

```md title="content/guide.md"
<!-- A file next to the page, bundled with it -->

![The editor](./editor.png)

<!-- A file in `public/`, with the base path added -->

![The logo](/logo.png)

<!-- A remote image -->

![A photo](https://images.example.com/photo.jpg)
```

![A page of the docs](/screenshots/light.png)

The same paths work in an `<img>` tag and in [`<ImageZoom>`](/markdown/components#image-zoom).

### Image Component [#image-component]

In a custom page or a component, [`Image`](/client-api#image) from `vuesho/client` renders an image with the same lazy loading, placeholders and optimization:

```vue title="src/pages/index.vue"
<script setup lang="ts">
import { Image, addBasePath } from "vuesho/client";
</script>

<template>
  <Image :src="addBasePath('/hero.png')" :width="1200" :height="630" alt="The editor" preload />
</template>
```

To replace the component that renders every image, including Markdown images and `ImageZoom`, fill the `image` [slot](/theme#slots).

## Image Sizes [#image-sizes]

The build reads the width and height of each local and remote image, except SVG images. Configure this with `markdown.imageSize`, or turn it off with `imageSize: false`:

```ts title="vuesho.config.ts"
createSite(docs.toSource()).config({
  markdown: {
    // Skip remote images, and leave an image without a size when its file can't be read
    imageSize: { external: false, onError: "ignore" },
  },
});
```

### ImageSizeOptions

| Prop        | Type                                                                     | Description                                                           |
| ----------- | ------------------------------------------------------------------------ | --------------------------------------------------------------------- |
| `external?` | `boolean \| { timeout?: number; } \| undefined`                          | Reads external image sizes over the network. Default: `true`          |
| `onError?`  | `"error" \| "ignore" \| "hide" \| ((error: Error) => void) \| undefined` | What to do with an image whose size can't be read. Default: `"error"` |

<Callout type="warn" title="Missing Images">
The build fails at the line of an image whose file doesn't exist, or whose request fails. `vuesho dev` shows the error when you open the page.
</Callout>

## Placeholders [#placeholders]

With `imagePlaceholder: "blur"`, a blurred copy of each image shows until the image loads. The build creates the copies with [sharp](https://sharp.pixelplumbing.com):

```npm
npm i -D sharp
```

```ts title="vuesho.config.ts"
createSite(docs.toSource()).config({
  markdown: { imagePlaceholder: "blur" },
});
```

Placeholders work for JPEG, PNG, WebP and AVIF files next to the page or in `public/`, unless they're animated. Remote images, and images in a [dynamic source](/dynamic-rendering), have none.

## Optimization [#optimization]

An image optimizer resizes each image to the widths that screens need, and serves it in a format like WebP. `vuesho dev` serves the original files, while a deployed site uses its host's optimizer:

<Tabs :items='["Vercel","Netlify","Cloudflare","Node.js","Static host"]'>
<Tab value="Vercel">
The [recommended preset](/config#recommendedpreset) includes `vercelImage()`, which turns on [Vercel Image Optimization](https://vercel.com/docs/image-optimization) when the site deploys to Vercel.
</Tab>

<Tab value="Netlify">
The [recommended preset](/config#recommendedpreset) includes `netlifyImage()`, which turns on the [Netlify Image CDN](https://docs.netlify.com/build/image-cdn/overview/) when the site deploys to Netlify.
</Tab>

<Tab value="Cloudflare">
Turn on [image transformations](https://developers.cloudflare.com/images/transform-images/transform-via-url/) for your site's zone, then add `cloudflareImage()`:

```ts title="vuesho.config.ts"
import { cloudflareImage } from "vuesho/config"; // [!code ++]

createSite(docs.toSource()).plugins(
  recommendedPreset(),
  cloudflareImage(), // [!code ++]
);
```

The build doesn't check remote images against `remotePatterns` here, since Cloudflare checks them against the hosts in the zone's settings.
</Tab>

<Tab value="Node.js">
`selfHostedImage()` optimizes images with [sharp](https://sharp.pixelplumbing.com) on the site's server, and in `vuesho dev`. Once deployed, it fetches each image of the site from the [site URL](/seo#site-url), so the build needs `site.baseUrl`:

```npm
npm i sharp
```

```ts title="vuesho.config.ts"
import { selfHostedImage } from "vuesho/image/self-hosted"; // [!code ++]

createSite(docs.toSource())
  .plugins(
    recommendedPreset(),
    selfHostedImage(), // [!code ++]
  )
  .config({ site: { baseUrl: "https://docs.acme.dev" } });
```

`selfHostedImage()` needs a server, so a [static build](/deploying#static-hosting) with it fails. The server caches each optimized image in [Nitro's cache](https://nitro.build/docs/cache).
</Tab>

<Tab value="Static host">
A static host without an image service, like GitHub Pages, serves the original files, which keep their sizes and placeholders. A static build deployed to Vercel or Netlify still uses the host's optimizer.
</Tab>
</Tabs>

Optimizers skip SVG images, `data:` URLs and an `Image` with `unoptimized`. With `dangerouslyAllowSVG: true`, Vercel and Cloudflare optimize SVG images too.

### Optimizer Options [#optimizer-options]

To configure Vercel's or Netlify's optimizer, set `image: false` on the recommended preset, and add the optimizer yourself:

```ts title="vuesho.config.ts"
import { createSite, recommendedPreset, vercelImage } from "vuesho/config"; // [!code highlight]
import { defineDocs } from "vuesho/content";

const docs = defineDocs();

export default createSite(docs.toSource()).plugins(
  recommendedPreset({ image: false }), // [!code highlight]
  vercelImage({ formats: ["image/avif", "image/webp"], minimumCacheTTL: 3600 }), // [!code ++]
);
```

<Tabs :items='["Vercel","Netlify","Cloudflare","Node.js"]'>
<Tab value="Vercel">
### VercelImageOptions

| Prop                      | Type                                            | Description                                                                                                          |
| ------------------------- | ----------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- |
| `deviceSizes?`            | `number[] \| undefined`                         | The screen widths an image fills. Default: `those of Next.js, from 640 to 3840`                                      |
| `imageSizes?`             | `number[] \| undefined`                         | The widths it serves below `deviceSizes`, for images narrower than the screen. Default: `16 to 384`                  |
| `qualities?`              | `number[] \| undefined`                         | The qualities it serves. An image gets the one closest to its `quality`. Default: `any`                              |
| `remotePatterns?`         | `RemotePattern[] \| undefined`                  | The remote images it optimizes. Vercel refuses images that none of them match.                                       |
| `localPatterns?`          | `LocalPattern[] \| undefined`                   | The site's images it optimizes. Vercel refuses images that none of them match. Default: `every one`                  |
| `formats?`                | `("image/avif" \| "image/webp")[] \| undefined` | The formats it serves to browsers that accept them. Default: `["image/webp"]`                                        |
| `minimumCacheTTL?`        | `number \| undefined`                           | The minimum time it keeps an optimized image, in seconds.                                                            |
| `dangerouslyAllowSVG?`    | `boolean \| undefined`                          | Optimizes SVG images too, which can run scripts. Default: `false`                                                    |
| `contentSecurityPolicy?`  | `string \| undefined`                           | The `Content-Security-Policy` for optimized images.                                                                  |
| `contentDispositionType?` | `"inline" \| "attachment" \| undefined`         | The `Content-Disposition` for optimized images. With `attachment`, a browser that opens an image's URL downloads it. |
</Tab>

<Tab value="Netlify">
### NetlifyImageOptions

| Prop              | Type                           | Description                                                                                                                                        |
| ----------------- | ------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------- |
| `remotePatterns?` | `RemotePattern[] \| undefined` | The remote images it optimizes, which the plugin writes as regular expressions in `remote_images`. Netlify refuses images that none of them match. |
| `qualities?`      | `number[] \| undefined`        | The qualities it serves, from 1 to 100. An image gets the one closest to its `quality`. Default: `any`                                             |
</Tab>

<Tab value="Cloudflare">
### CloudflareImageOptions

| Prop                   | Type                                                                   | Description                                                                                                                                                                                                                                                                    |
| ---------------------- | ---------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `path?`                | `string \| undefined`                                                  | The path that transforms images on the zone. Default: `"/cdn-cgi/image"`                                                                                                                                                                                                       |
| `deviceSizes?`         | `number[] \| undefined`                                                | The screen widths an image fills. Default: `those of Next.js, from 640 to 3840`                                                                                                                                                                                                |
| `imageSizes?`          | `number[] \| undefined`                                                | The widths it serves below `deviceSizes`, for images narrower than the screen. Default: `16 to 384`                                                                                                                                                                            |
| `qualities?`           | `number[] \| undefined`                                                | The qualities it serves, from 1 to 100. An image gets the one closest to its `quality`. Default: `any`                                                                                                                                                                         |
| `format?`              | `"auto" \| "avif" \| "webp" \| "jpeg" \| "png" \| undefined`           | The format it serves. Cloudflare's `json`, which Fumapress's `cloudflareImage` accepts, is left out: it answers with the image's size and format instead of the image, so every image on the site would fail to load. Default: `"auto", the best one that the browser accepts` |
| `fit?`                 | `"scale-down" \| "contain" \| "cover" \| "crop" \| "pad" \| undefined` | How an image fits the width.                                                                                                                                                                                                                                                   |
| `dangerouslyAllowSVG?` | `boolean \| undefined`                                                 | Transforms SVG images too. Default: `false`                                                                                                                                                                                                                                    |
</Tab>

<Tab value="Node.js">
### SelfHostedImageOptions

| Prop                   | Type                           | Description                                                                                                                                                                       |
| ---------------------- | ------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `path?`                | `string \| undefined`          | The path of the route that optimizes images, without the base path. Default: `"/_vuesho/image"`                                                                                   |
| `remotePatterns?`      | `RemotePattern[] \| undefined` | The remote images it optimizes, which should come from hosts you trust. The route refuses images that none of them match.                                                         |
| `deviceSizes?`         | `number[] \| undefined`        | The screen widths an image fills. Default: `those of Next.js, from 640 to 3840`                                                                                                   |
| `imageSizes?`          | `number[] \| undefined`        | The widths it serves below `deviceSizes`, for images narrower than the screen. Default: `16 to 384`                                                                               |
| `qualities?`           | `number[] \| undefined`        | The qualities it serves, from 1 to 100. An image gets the one closest to its `quality`, and the route refuses any other. Default: `any`                                           |
| `minimumCacheTTL?`     | `number \| undefined`          | How many seconds the server and browser keep an optimized image, or the `max-age` of the image's own response when that is longer. Default: `` 14400, 4 hours, as `next/image` `` |
| `fetchTimeout?`        | `number \| undefined`          | How long it waits for an image, in milliseconds. Default: `4000`                                                                                                                  |
| `maximumResponseBody?` | `number \| undefined`          | The largest image it optimizes, in bytes. Default: `64 MB`                                                                                                                        |
</Tab>
</Tabs>

### Remote Images [#remote-images]

An optimizer fetches only the remote images that its `remotePatterns` match. A page with a remote image that no pattern matches fails the build:

```ts title="vuesho.config.ts"
createSite(docs.toSource()).plugins(
  recommendedPreset({ image: false }),
  vercelImage({
    remotePatterns: [{ protocol: "https", hostname: "images.example.com" }], // [!code highlight]
  }),
);
```

A pattern matches each part of a URL, and a part it leaves out matches anything. With `selfHostedImage()`, a redirect's target must match too.

### RemotePattern

| Prop        | Type                             | Description                                                                             |
| ----------- | -------------------------------- | --------------------------------------------------------------------------------------- |
| `protocol?` | `"http" \| "https" \| undefined` |                                                                                         |
| `hostname`  | `string`                         | The host. `*` matches one label and a leading `**` any number, like `"**.example.com"`. |
| `port?`     | `string \| undefined`            | The port, or `""` for a URL without one.                                                |
| `pathname?` | `string \| undefined`            | The path. `*` matches one segment and a trailing `**` any number, like `"/avatars/**"`. |
| `search?`   | `string \| undefined`            | The query, like `"?v=2"`, or `""` for a URL without one.                                |

<Callout type="warn" title="Pages Rendered on Request">
The build doesn't check the pages of a [dynamic source](/dynamic-rendering). List their image hosts in `remotePatterns`, or those images won't load on the deployed site.
</Callout>

### Other Optimizers [#other-optimizers]

A plugin can add another image service. Its `rootProps` hook returns `image` with a URL template. Vuesho fills the template's `{src}`, `{width}` and `{quality}` for each image:

```ts title="acme-image.ts"
import type { AppShape, Plugin } from "vuesho/config";

export function acmeImage<C extends AppShape>(): Plugin<C> {
  return {
    name: "acme-image",
    rootProps: () => ({
      image: {
        url: "https://images.acme.dev/{src}?w={width}&q={quality}",
        deviceSizes: [640, 750, 828, 1080, 1200, 1920, 2048, 3840],
      },
    }),
  };
}
```

### ImageOptimizer

| Prop                   | Type                           | Description                                                                                                |
| ---------------------- | ------------------------------ | ---------------------------------------------------------------------------------------------------------- |
| `url`                  | `string`                       | The URL for `{src}` at `{width}` and `{quality}`, like `"/_vercel/image?url={src}&w={width}&q={quality}"`. |
| `deviceSizes`          | `number[]`                     | The screen widths an image fills, ascending.                                                               |
| `imageSizes?`          | `number[] \| undefined`        | The widths it serves below `deviceSizes`, ascending. Default: `any width`                                  |
| `qualities?`           | `number[] \| undefined`        | The qualities it serves, from 1 to 100. Default: `any quality`                                             |
| `dangerouslyAllowSVG?` | `boolean \| undefined`         | Whether it optimizes SVG images.                                                                           |
| `remotePatterns?`      | `RemotePattern[] \| undefined` | The remote images it optimizes. A generated page with any other fails the build.                           |
| `localPatterns?`       | `LocalPattern[] \| undefined`  | The site's images it optimizes. A generated page with any other fails the build. Default: `all`            |

When the optimizer has `remotePatterns`, the build checks the remote images against them.
