Skip to content

astro

ImageKit & Astro

Astro

ImageKit & Astro

ImageKit & Astro

ImageKit is a real-time media optimization and delivery platform with a global CDN, a built-in Digital Asset Manager (DAM), and a URL-based transformation API for images and videos.

When delivering through ImageKit, you get automatic format conversion (AVIF, WebP), automatic quality, responsive images, AI-powered transformations (background removal, generative fill, upscaling), and adaptive video streaming.

Using ImageKit in Astro

The ImageKit Astro SDK registers a custom image service that re-routes Astro's built-in <Image /> and <Picture /> components, plus Markdown and MDX images, through ImageKit. Local imports continue to be processed by Astro's built-in Sharp service. This means an existing project can add the integration without breaking existing assets.

The SDK also provides a <Video /> component, an <OgImage /> component for social cards, and a server-side helper for issuing client-side upload tokens.

For pure URL building or browser uploads in any framework, you can also use the lower-level ImageKit JavaScript SDK. For server-side asset management (uploading, listing, deleting, metadata), use the ImageKit Node.js SDK.

Prerequisites

Installing the ImageKit Astro SDK

Install the SDK by running the appropriate command for your package manager:

```shell npm install @imagekit/astro ``` ```shell pnpm add @imagekit/astro ``` ```shell yarn add @imagekit/astro ```

Configuring your account

Create a new .env file in the root of your project and add your ImageKit credentials:

IMAGEKIT_URL_ENDPOINT="https://ik.imagekit.io/<your_imagekit_id>"

# Only needed if you generate upload auth tokens on the server
PUBLIC_IMAGEKIT_PUBLIC_KEY="<Your Public Key>"
IMAGEKIT_PRIVATE_KEY="<Your Private Key>"

Then register the integration in astro.config.mjs:


You can also pass urlEndpoint directly to the integration instead of using the environment variable:

imagekit({
  urlEndpoint: 'https://ik.imagekit.io/<your_imagekit_id>',
}),

Using ImageKit images

With the integration installed, Astro's built-in <Image /> and <Picture /> components route requests through ImageKit and apply automatic format and quality optimization, responsive srcset, and lazy loading.

---

---
<Image
  src="/sample.jpg"
  width={800}
  height={600}
  alt="A sample image"
/>

The integration adds an additional transformation prop on <Image />, <Picture />, and getImage() for applying any ImageKit transformation (e.g. cropping, focus, AI effects, overlays):

---

---
<Image
  src="/portrait.jpg"
  width={500}
  height={500}
  alt="Cropped portrait"
  transformation={[{ width: 500, height: 500, focus: 'face' }]}
/>

The component-level width and height set the rendered HTML dimensions. The values inside transformation control the ImageKit server-side resize.

AI-powered transformations

ImageKit transformations include AI effects that can be applied through the same transformation prop:

---

---
<!-- Remove background -->
<Image
  src="/product.jpg"
  width={500}
  height={500}
  alt="Product with background removed"
  transformation={[{ aiRemoveBackground: true }]}
/>

<!-- Upscale a low-resolution image -->
<Image
  src="/thumbnail.jpg"
  width={1024}
  height={1024}
  alt="Upscaled image"
  transformation={[{ aiUpscale: true }]}
/>

<!-- Generative fill to extend an image to a new aspect ratio -->
<Image
  src="/portrait.jpg"
  width={1600}
  height={900}
  alt="Image extended with generative fill"
  transformation={[
    { width: 1600, height: 900, cropMode: 'pad_resize', background: 'genfill' },
  ]}
/>

<!-- AI drop shadow -->
<Image
  src="/product.png"
  width={500}
  height={500}
  alt="Product with AI drop shadow"
  transformation={[{ aiDropShadow: true }]}
/>

See the supported transformations reference in ImageKit documentation for the full list, including overlays, smart cropping (focus: 'auto', focus: 'face'), and other effects.

Using ImageKit videos

Add videos to your .astro components with the <Video /> component. It accepts standard HTML video attributes alongside ImageKit-specific props such as transformation and urlEndpoint.

---

---
<Video
  src="/sample.mp4"
  width={1280}
  height={720}
  controls
/>

To resize the video on ImageKit's side, pass dimensions inside transformation:

<Video
  src="/sample.mp4"
  width={640}
  height={360}
  transformation={[{ width: 640, height: 360 }]}
  controls
/>

ImageKit Video Player

The @imagekit/video-player package exports a dedicated Astro integration through the @imagekit/video-player/astro subpath. It provides a native IKVideoPlayer Astro component with full TypeScript types (IKPlayerOptions, SourceOptions). You can use it directly in .astro files without any framework adapter.

The player is built on Video.js and includes AI-generated subtitles and chapters, automatic translation into 50+ languages, word-level karaoke-style highlighting, seek thumbnails, a floating sticky player, and adaptive bitrate streaming (HLS/DASH). No manual transcription work is required.

Install the package:

```shell npm install @imagekit/video-player ``` ```shell pnpm add @imagekit/video-player ``` ```shell yarn add @imagekit/video-player ```

Then use the IKVideoPlayer component in any .astro file:

---


const ikOptions = {
  imagekitId: 'YOUR_IMAGEKIT_ID',
  seekThumbnails: true,
};

const source = {
  src: 'https://ik.imagekit.io/your_imagekit_id/video.mp4',
  chapters: true,          // AI-generated chapter markers
  textTracks: [{
    autoGenerate: true,    // AI speech-to-text subtitles
    default: true,
    highlightWords: true,  // word-level highlighting
    translations: [
      { langCode: 'es', label: 'Spanish' },
      { langCode: 'fr', label: 'French' },
    ],
  }],
};
---

<IKVideoPlayer ikOptions={ikOptions} source={source} />

With chapters: true, the player auto-generates chapter markers from the video content. Setting autoGenerate: true in textTracks creates AI speech-to-text subtitles without any .srt files. Each entry in translations adds an automatically generated subtitle track in that language.

:::note The Video Player SDK is currently in beta. Test thoroughly before using it in production. See the Video Player overview in ImageKit documentation for the full list of options, including playlists, shoppable videos, and signed URL support. :::

Generating Open Graph image URLs

Use the <OgImage /> component to render OpenGraph and Twitter Card <meta> tags pointing at an ImageKit-optimized image. Place it inside your layout's <head>.

---

---
<html>
  <head>
    <OgImage
      src="/og-banner.jpg"
      title="My page title"
      description="Preview description for social cards"
      alt="OG image description"
    />
  </head>
  <body><slot /></body>
</html>

If you need just a URL instead of the rendered tags, use the getOgImageUrl() helper:

---

const ogImage = getOgImageUrl({
  src: '/og-banner.jpg',
  transformation: [{ width: 1200, height: 630 }],
});
---
<meta property="og:image" content={ogImage} />

See the ImageKit OG component documentation for a complete list of supported props.

Enabling client-side uploads

To upload files directly from the browser, generate a short-lived authentication token on the server using the getUploadAuthParams() helper from @imagekit/astro/server. The private key stays server-side and is never sent to the browser.

This requires an adapter so the endpoint runs on demand:




  return new Response(JSON.stringify(authParams), {
    headers: { 'Content-Type': 'application/json' },
  });
};

The browser then fetches this endpoint and passes the returned signature, token, expire, and publicKey to the upload() function from @imagekit/javascript. Install it as a direct dependency:

```shell npm install @imagekit/javascript ``` ```shell pnpm add @imagekit/javascript ``` ```shell yarn add @imagekit/javascript ```

A minimal upload form on a .astro page:

<input type="file" id="file-input" />
<button id="upload-btn">Upload</button>
<progress id="upload-progress" value="0" max="100"></progress>

<script>
  import { upload } from '@imagekit/javascript';

  const fileInput = document.getElementById('file-input') as HTMLInputElement;
  const uploadBtn = document.getElementById('upload-btn') as HTMLButtonElement;
  const progress = document.getElementById('upload-progress') as HTMLProgressElement;

  uploadBtn.addEventListener('click', async () => {
    const file = fileInput.files?.[0];
    if (!file) return;

    const auth = await fetch('/api/upload-auth').then((r) => r.json());

    const result = await upload({
      ...auth,
      file,
      fileName: file.name,
      onProgress: (e) => {
        progress.value = (e.loaded / e.total) * 100;
      },
    });

    console.log('Uploaded:', result);
  });
</script>

See the ImageKit guide for full error handling and abort signals.

Loading from your ImageKit Media Library

You can use Astro Content Collections together with the @imagekit/nodejs SDK to power gallery and listing pages directly from your ImageKit Media Library.

Install the Node SDK as a dev dependency:

```shell npm install -D @imagekit/nodejs ``` ```shell pnpm add -D @imagekit/nodejs ``` ```shell yarn add -D @imagekit/nodejs ```

Then define a collection backed by client.assets.list(). The Node SDK returns an array of File | Folder objects. To limit results to images, pass type: 'file' to exclude folders and fileType: 'image'. Use the Files.File type guard so each entry is correctly typed before mapping it into your collection schema:





const client = new ImageKit({
  privateKey: import.meta.env.IMAGEKIT_PRIVATE_KEY,
});

const gallery = defineCollection({
  loader: async () => {
    const assets = await client.assets.list({
      type: 'file',       // exclude folders
      fileType: 'image',  // only image files
      skip: 0,
      limit: 50,
    });

    return assets
      .filter((asset): asset is Files.File =>
        asset.type === 'file' && !!asset.fileId && !!asset.url
      )
      .map((asset) => ({
        id: asset.fileId ?? '',
        url: asset.url ?? '',
        width: asset.width ?? 0,
        height: asset.height ?? 0,
        name: asset.name ?? '',
        tags: asset.tags ?? [],
      }));
  },
  schema: z.object({
    url: z.string().url(),
    width: z.number(),
    height: z.number(),
    name: z.string(),
    tags: z.array(z.string()),
  }),
});

After adding the collection, run astro sync (or start the dev server) to generate the collection types used by getCollection().

Render the collection with <Image> from astro:assets. The integration generates the ImageKit CDN URL with the requested transformations:

---


const photos = await getCollection('gallery');
---
{photos.map(({ data }) => (
  <Image
    src={data.url}
    width={data.width}
    height={data.height}
    alt={data.name}
    transformation={[{ width: 400, height: 300, focus: 'auto' }]}
  />
))}

Using ImageKit in Node.js

For server-side workflows such as bulk uploads, listing assets, or deleting files, use the official @imagekit/nodejs SDK directly:


const client = new ImageKit({
  privateKey: import.meta.env.IMAGEKIT_PRIVATE_KEY,
});

await client.files.upload({
  file: '<file path, buffer, or URL>',
  fileName: 'sample.jpg',
});

Official resources