Getting started

Integration & migration

Image & video API

Video Player SDK

DAM user guide

API overview

Account

Astro ImageKit SDK

Real-time image & video resizing, automatic optimization, and file uploading in Astro using ImageKit.io.


The Astro ImageKit SDK is a framework-specific integration built on top of the ImageKit JavaScript SDK. It seamlessly integrates ImageKit's URL generation, image and video optimizations, and file upload capabilities with Astro.

The SDK is lightweight, has first-class TypeScript support, and works with Astro 3 and above. You can view the source code on Github.

Installation and Setup

Install the Astro SDK via npm, pnpm, or yarn:

Copy
npm install @imagekit/astro
# or
pnpm add @imagekit/astro
# or
yarn add @imagekit/astro

Configure the Integration

Add the ImageKit integration to your Astro config:

Copy
// astro.config.mjs
import { defineConfig } from 'astro/config';
import imagekit from '@imagekit/astro/integration';

export default defineConfig({
  integrations: [imagekit()],
});

Set your ImageKit URL endpoint in a .env file:

Copy
# Preferred — available in both server and client code
PUBLIC_IMAGEKIT_URL_ENDPOINT=https://ik.imagekit.io/your_imagekit_id

# Server-only fallback
IMAGEKIT_URL_ENDPOINT=https://ik.imagekit.io/your_imagekit_id

Get your URL endpoint from the ImageKit dashboard.

The integration automatically configures:

  • image.service — sets Astro's image service to @imagekit/astro/image-service
  • image.domains — allows ik.imagekit.io and any hostname derived from your urlEndpoint
  • image.remotePatterns — adds secure (https) patterns for ImageKit hosts

You can also pass options directly to the integration:

Copy
export default defineConfig({
  integrations: [
    imagekit({
      urlEndpoint: import.meta.env.PUBLIC_IMAGEKIT_URL_ENDPOINT,
      transformationPosition: 'query', // or 'path'
      domains: ['assets.example.com'],
      remotePatterns: [{ protocol: 'https', hostname: 'assets.example.com', pathname: '/**' }],
    }),
  ],
});
Option Description
urlEndpointThe ImageKit URL endpoint. If omitted, falls back to PUBLIC_IMAGEKIT_URL_ENDPOINT or IMAGEKIT_URL_ENDPOINT environment variables.
transformationPositionWhere to place transformations in the URL: "query" (default, ?tr=...) or "path" (/tr:.../).
domainsAdditional hostnames to allow in Astro's image config. Merged with defaults.
remotePatternsAdditional Astro remote patterns to allow. Merged with defaults.

Standalone Image Service (Alternative)

If you want full control over Astro's image configuration — for example, you already manage image.domains and image.remotePatterns — you can use the ImageKit image service directly without the integration:

Copy
// astro.config.mjs
import { defineConfig } from 'astro/config';

export default defineConfig({
  image: {
    service: {
      entrypoint: '@imagekit/astro/image-service',
      config: {
        urlEndpoint: import.meta.env.PUBLIC_IMAGEKIT_URL_ENDPOINT,
        transformationPosition: 'query',
      },
    },
    domains: ['ik.imagekit.io'],
    remotePatterns: [{ protocol: 'https', hostname: 'ik.imagekit.io', pathname: '/**' }],
  },
});

When using the standalone service, you are responsible for keeping domains and remotePatterns in sync with your ImageKit URL endpoint. The integration handles this automatically.

Integration vs Standalone Image Service

Integration (@imagekit/astro/integration)Standalone (@imagekit/astro/image-service)
SetupOne-line Astro integrationManual image config
Auto-configures domains/patternsYesNo
Auto-sets image serviceYesN/A (you set it yourself)
FlexibilityGood for most projectsFull control when you have custom image config

For most projects, use the integration. Use the standalone service only if you have a specific reason to manage image config manually.

Exported Components, Utilities, and Types

Besides Image and Video, the SDK exports utility functions and error classes that can be used independently of the components.

Utility functions

  • buildSrc – Generates URLs for images and videos based on your URL endpoint and transformation parameters.
  • buildTransformationString – Converts array of transformation objects into a URL query string.
  • getResponsiveImageAttributes – Generates responsive src, srcSet, and sizes attributes.
  • upload – Facilitates file uploads to ImageKit with built-in support for common error handling, progress tracking, and abort functionality.

Refer to linked documentation for detailed usage of these utility functions.

Error classes for upload error handling

  • ImageKitInvalidRequestError — For invalid requests.
  • ImageKitAbortError — For aborted uploads.
  • ImageKitUploadNetworkError — For network errors during upload.
  • ImageKitServerError — For server-side errors.

Astro-specific exports

  • Image – A wrapper around Astro's built-in <Image /> component with ImageKit transformations and responsive image generation.
  • Video – A lightweight wrapper for the HTML <video> element that generates ImageKit-optimized video URLs.
  • getOgImageTags – Builds OpenGraph and Twitter Card meta tags with ImageKit-optimized image URLs.
  • getUploadAuthParams – Server-side helper that generates authentication parameters for client-side uploads.

Type definitions

The SDK provides TypeScript definitions for all components and utility functions, ensuring type safety and autocompletion in your IDE. Exported types include ImageProps, VideoProps, OgImageTagOptions, OgMetaTag, SrcOptions, UploadOptions, UploadResponse, and Transformation.

Image Component

The Image component wraps Astro's built-in <Image /> component. It gives you Astro's native image optimization features (lazy loading, responsive images, layout modes) while adding ImageKit's URL-based transformations.

It supports all Astro Image props and additionally accepts the following ImageKit-specific props:

Notes

  1. src should be a relative path (appended to urlEndpoint) or an absolute ImageKit URL. It does not accept statically imported image files.
  2. If width is not provided, the image service attempts to infer dimensions automatically (requires Astro 4.12+). For best results, always provide explicit width and height.
Parameter Description and Example

urlEndpoint

The base URL endpoint from your ImageKit dashboard. If omitted, the value from PUBLIC_IMAGEKIT_URL_ENDPOINT or IMAGEKIT_URL_ENDPOINT environment variable is used.

Example: https://ik.imagekit.io/your_imagekit_id

src
(Required)

A relative or absolute path to the image.

  • If a relative path is provided, it is appended to the urlEndpoint.
  • If an absolute path is provided, it is used as-is and the urlEndpoint is ignored.
  • Do not include query parameters directly in the src. Use the queryParameters prop instead.
  • When using a web proxy, you can pass the full image URL and prepend it with a /. For example - /https://example.com/image.jpg.
  • Do not pass a statically imported image

Examples:
Relative — /default-image.jpg
Absolute — https://ik.imagekit.io/demo/default-image.jpg Web Proxy - /https://example.com/image.jpg

transformation

An array of transformation objects. Each object can include properties like width, height, rotation, overlays, and advanced effects.

Example: [{ width: 300, height: 300 }]

See all supported transformation options.

queryParameters

An object with additional query parameters to append to the URL.

Example: {{ version: "v1" }}

responsiveA boolean that determines if responsive image functionality is enabled. Defaults to true, automatically generating srcSet and sizes attributes using ImageKit URLs. Set to false to disable this behavior and only apply explicitly defined transformations.
transformationPositionSpecifies whether the transformation string is included in the URL path or as a query parameter. Defaults to "query".
Example: "query" or "path"

deviceBreakpoints

Custom device-width breakpoints for responsive image generation.

Default: [640, 750, 828, 1080, 1200, 1920, 2048, 3840]

imageBreakpoints

Custom image-specific breakpoints for responsive image generation.

Default: [16, 32, 48, 64, 96, 128, 256, 384]

Basic Usage

Copy
---
import { Image } from '@imagekit/astro';
---

<Image
  urlEndpoint="https://ik.imagekit.io/your_imagekit_id"
  src="/default-image.jpg"
  alt="A sample image"
  width={400}
  height={300}
/>

When PUBLIC_IMAGEKIT_URL_ENDPOINT is configured in your .env, you can omit urlEndpoint:

Copy
---
import { Image } from '@imagekit/astro';
---

<Image
  src="/default-image.jpg"
  alt="A sample image"
  width={400}
  height={300}
/>

Image with Transformations

Copy
<Image
  src="/default-image.jpg"
  alt="Resized image"
  transformation={[{ width: 600, height: 400, focus: "auto" }]}
  width={600}
  height={400}
/>

Astro-Specific Props

The Image component supports all Astro <Image /> props, including:

Copy
<!-- Format and quality -->
<Image
  src="/photo.jpg"
  alt="WebP image"
  format="webp"
  quality={80}
  width={800}
  height={600}
/>

<!-- Layout modes (Astro 5+) -->
<Image
  src="/hero.jpg"
  alt="Full-width hero"
  layout="full-width"
  width={1200}
  height={630}
/>

<Image
  src="/hero.jpg"
  alt="Constrained hero"
  layout="constrained"
  width={800}
  height={400}
/>

<!-- Density-based srcset -->
<Image
  src="/icon.png"
  alt="Retina icon"
  densities={[1.5, 2]}
  width={100}
  height={100}
/>

<!-- Explicit widths with sizes -->
<Image
  src="/photo.jpg"
  alt="Responsive photo"
  widths={[240, 540, 720]}
  sizes="(max-width: 360px) 240px, (max-width: 720px) 540px, 720px"
  width={720}
  height={480}
/>

<!-- Loading and priority -->
<Image
  src="/hero.jpg"
  alt="Above the fold"
  loading="eager"
  fetchpriority="high"
  width={1200}
  height={630}
/>

Delivering Public Media via Web Proxy

If your source files already live on a public URL (for example, assets on another domain), you can use ImageKit Web Proxy and still use the Image component for transformations and optimization.

Web Proxy lets ImageKit fetch files from publicly accessible URLs and deliver them through your ImageKit URL endpoint, so you can apply all ImageKit transformations without migrating files first.

1. Configure Web Proxy in ImageKit

  1. In the ImageKit dashboard, go to External Storage and click Add New.
  2. Choose Web proxy as the origin type.
  3. Save the origin and make sure it is enabled for your URL endpoint (default endpoint or a custom one via origin preference).
  4. Ensure the source URL is publicly accessible from ImageKit.

Attaching a Web Proxy origin to a URL endpoint can allow access to any publicly accessible file through your account. In production, enable signed URL restrictions and follow ImageKit's URL signing best practices.

2. Use Web Proxy URLs with the Image component

When using Web Proxy, pass the original public URL as part of src (relative to your ImageKit endpoint):

Copy
<Image
  src="/https://www.example.com/images/hero.jpg"
  alt="Hero image from web proxy"
  width={1200}
  height={630}
  transformation={[{ width: 1200, height: 630, }]}
/>

With PUBLIC_IMAGEKIT_URL_ENDPOINT=https://ik.imagekit.io/your_imagekit_id, the generated URL pattern is:

Copy
https://ik.imagekit.io/your_imagekit_id/https://www.example.com/images/hero.jpg?tr=w-1200,h-630

You can also use path-style transformations by setting transformationPosition="path":

Copy
<Image
  src="/https://www.example.com/images/banner.jpg"
  alt="Banner from web proxy"
  width={900}
  height={400}
  transformation={[{ width: 900, height: 400 }]}
  transformationPosition="path"
/>

Generated URL pattern:

Copy
https://ik.imagekit.io/your_imagekit_id/tr:w-900,h-400/https://www.example.com/images/banner.jpg

3. Responsive delivery with Web Proxy

Web Proxy works with responsive image generation as well:

Copy
<Image
  src="/https://www.example.com/images/product.jpg"
  alt="Product image"
  width={800}
  height={600}
  layout="constrained"
/>

If you use signed URLs with Web Proxy, sign the encoded source URL as recommended by ImageKit (encode the complete public URL before signing).

Video Component

The Video component wraps the HTML <video> element and generates ImageKit-optimized video URLs with transformations. It supports all HTML video attributes and additionally accepts the ImageKit-specific props — urlEndpoint, transformation, transformationPosition, and queryParameters. For the definition of these props, refer to the Image component section.

Copy
---
import { Video } from '@imagekit/astro';
---

<Video
  urlEndpoint="https://ik.imagekit.io/your_imagekit_id"
  src="/sample-video.mp4"
  width={640}
  height={360}
  controls
/>

Video with Transformations

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

Video with HTML Attributes

Copy
<Video
  src="/sample-video.mp4"
  width={640}
  height={360}
  controls
  autoplay
  loop
  muted
  preload="none"
  poster="https://ik.imagekit.io/your_imagekit_id/video-thumbnail.jpg"
/>

Lazy Loading Videos

To lazy load a video, set preload to none and specify a poster image. You can use buildSrc to generate a thumbnail URL from the video:

Copy
---
import { Video, buildSrc } from '@imagekit/astro';

const posterUrl = buildSrc({
  urlEndpoint: "https://ik.imagekit.io/your_imagekit_id",
  src: "/video.mp4/ik-thumbnail.jpg",
});
---

<Video
  src="/video.mp4"
  controls
  preload="none"
  poster={posterUrl}
  width={640}
  height={360}
/>

Refer to the create thumbnail documentation for more details on generating a thumbnail from a video.

Height and Width Transformations

Resize images on the fly using the width and height transformation properties:

Copy
---
import { Image } from '@imagekit/astro';
---

<Image
  src="/profile.png"
  alt="Profile picture"
  width={500}
  height={500}
  transformation={[{ width: 500, height: 500 }]}
/>

The width and height props on the component control the rendered HTML dimensions. The width and height inside transformation control the ImageKit server-side resize. These can differ — for example, you might want a 1200px server resize but a 600px rendered width for retina displays.

Image Loading Optimization

Image loading optimization is crucial for web performance. The ImageKit Astro SDK automatically optimizes images with compression and format selection. You can further enhance performance by controlling how and when images load.

Eager Loading

For critical images like hero images or above-the-fold content, prioritize loading to improve Largest Contentful Paint (LCP) performance. The SDK provides multiple approaches:

The priority prop (or shorthand priority) automatically optimizes an image for critical rendering by setting optimal values for loading, decoding, and fetch priority:

Copy
<Image
  src="/hero.jpg"
  alt="Hero image"
  width={1200}
  height={630}
  priority
/>

<!-- Output HTML includes -->
<!-- loading="eager" decoding="sync" fetchpriority="high" -->

This sets:

  • loading="eager" – load immediately instead of deferring
  • decoding="sync" – synchronously decode to avoid rendering delay
  • fetchpriority="high" – signal to the browser to prioritize this resource

Using Individual HTML Attributes

For more control, set loading attributes individually:

Copy
<!-- Eager loading -->
<Image
  src="/hero.jpg"
  alt="Hero image"
  width={1200}
  height={630}
  loading="eager"
  decoding="sync"
  fetchpriority="high"
/>

<!-- Lazy loading (default) -->
<Image
  src="/article-image.jpg"
  alt="Article image"
  width={800}
  height={600}
  loading="lazy"
  decoding="async"
/>

Format and Quality Optimization

Optimize file size while maintaining quality:

Copy
<!-- WebP format with high quality -->
<Image
  src="/photo.jpg"
  alt="High quality photo"
  width={800}
  height={600}
  format="webp"
  quality="high"
/>

<!-- AVIF format for maximum compression -->
<Image
  src="/photo.jpg"
  alt="Compressed photo"
  width={800}
  height={600}
  format="avif"
  quality={85}
/>

<!-- Quality presets: low, mid, high, max -->
<Image
  src="/photo.jpg"
  alt="Balanced quality"
  width={800}
  height={600}
  quality="mid"
/>

Responsive Images

Responsive images adapt to different screen sizes and device capabilities, reducing bandwidth usage and improving performance. The ImageKit Astro SDK supports multiple methods for creating responsive images. Understanding the different approaches and their precedence is important for optimal results.

When responsive is true (the default), the SDK automatically generates srcSet and sizes attributes using ImageKit's intelligent breakpoint system:

Copy
<Image
  src="/photo.jpg"
  alt="Responsive photo"
  width={800}
  height={600}
/>

<!-- Generated output includes srcset with multiple widths -->
<!-- srcset="...?tr=w-640/... 640w, ...?tr=w-750/... 750w, ...?tr=w-828/... 828w, ..., ...?tr=w-1920/... 1920w" -->
<!-- sizes="100vw" -->

This uses default device breakpoints: [640, 750, 828, 1080, 1200, 1920, 2048, 3840] and generates optimal image variants for common device widths.

Using the densities Prop

For pixel density-based responsive images (good for fixed-size elements like logos or icons), use densities:

Copy
<!-- Pixel density variants for crisp display on high-DPI screens -->
<Image
  src="/icon.png"
  alt="App icon"
  width={100}
  height={100}
  densities={[1, 1.5, 2]}
/>

<!-- Generated: icon.png?tr=w-100 1x, icon.png?tr=w-150 1.5x, icon.png?tr=w-200 2x -->

This is ideal for icons, logos, and other fixed-size graphics where you want to support retina displays without changing the display dimensions.

Using the widths Prop with sizes

For explicit control over which widths are generated in the srcset:

Copy
<!-- Custom widths for specific design breakpoints -->
<Image
  src="/photo.jpg"
  alt="Gallery image"
  width={800}
  height={600}
  widths={[300, 600, 900, 1200]}
  sizes="(max-width: 640px) 300px, (max-width: 1024px) 600px, 900px"
/>

<!-- Generated srcset includes only specified widths -->
<!-- srcset="...?tr=w-300/... 300w, ...?tr=w-600/... 600w, ...?tr=w-900/... 900w, ...?tr=w-1200/... 1200w" -->

Both widths and sizes must be provided together. This approach gives you complete control over responsive variants.

Using the layout Prop (Astro 5.10+)

The layout prop determines how the image resizes and automatically generates appropriate srcset and sizes:

Copy
<!-- Constrained layout: scales down but never up -->
<Image
  src="/photo.jpg"
  alt="Article image"
  width={800}
  height={600}
  layout="constrained"
/>

<!-- Full width: always fills container width -->
<Image
  src="/hero.jpg"
  alt="Hero image"
  width={1920}
  height={1080}
  layout="full-width"
/>

<!-- Fixed: maintains exact dimensions, supports density scaling -->
<Image
  src="/logo.png"
  alt="Logo"
  width={200}
  height={100}
  layout="fixed"
/>

<!-- None: no automatic responsive behavior -->
<Image
  src="/custom.jpg"
  alt="Custom handling"
  width={400}
  height={300}
  responsive={false}
/>

When using a layout, srcSet and sizes are automatically generated based on the layout type and image dimensions.

Custom Breakpoints

Customize the breakpoints used for responsive image generation:

Copy
<Image
  src="/photo.jpg"
  alt="Custom breakpoints"
  width={800}
  height={600}
  deviceBreakpoints={[320, 480, 768, 1024, 1280]}
  imageBreakpoints={[48, 96, 192, 384]}
/>
  • deviceBreakpoints: Common device viewport widths for generating width-based variants
  • imageBreakpoints: Image-specific sizes, typically smaller for generating compact variants

Disabling Responsive Images

If you need manual control or have custom responsive handling:

Copy
<Image
  src="/photo.jpg"
  alt="Non-responsive"
  width={800}
  height={600}
  responsive={false}
/>

<!-- No srcset or sizes generated -->

Responsive Method Precedence

When multiple responsive methods are combined, they follow this precedence order:

  1. Explicit srcset + sizes attribute – Takes precedence over all SDK-generated responsive behavior
  2. Astro densities prop – When provided, disables ImageKit responsive and uses Astro's density-based srcset
  3. Astro widths + sizes props – Generates width-based srcset using Astro's image service. The widths passed are combined with imagekit's device and image breakpoints and used to generate a comprehensive srcset.
  4. Astro layout prop – Auto-generates srcset and sizes based on layout type. The layout props internalls generates widths, that are combined with imagekit's device and image breakpoints and used to generate a comprehensive srcset.
  5. ImageKit responsive=true (default) – Automatically generates responsive srcset with intelligent breakpoints.
Copy
<!-- Example: layout has higher precedence than ImageKit responsive -->
<Image
  src="/photo.jpg"
  width={800}
  height={600}
  layout="constrained"
  responsive={true}  <!-- Will be overridden by layout -->
/>
<!-- Result: uses layout-based srcset, not ImageKit responsive -->

<!-- Example: widths + sizes override ImageKit responsive -->
<Image
  src="/photo.jpg"
  width={800}
  height={600}
  widths={[300, 600, 900]}
  sizes="(max-width: 640px) 300px, 600px"
  responsive={true}  <!-- Will be overridden by widths -->
/>
<!-- Result: uses Astro's width-based srcset -->

Best practice: Use one responsive method per image. For most cases, rely on the default responsive=true behavior, which automatically optimizes for your needs.

Lazy Loading Images

The Image component lazy loads images by default. You can control this behavior using the loading prop.

Copy
<!-- Default: lazy loading -->
<Image
  src="/profile.png"
  alt="Lazy loaded"
  width={500}
  height={500}
/>

<!-- Eager loading for above-the-fold images -->
<Image
  src="/hero.jpg"
  alt="Hero image"
  loading="eager"
  width={1200}
  height={630}
/>

Lazy Loading with Placeholder

You can show a low-quality blurred placeholder while the full image loads by using ImageKit's buildSrc utility function to generate a placeholder URL and setting it as a background-image on the <Image> element. Then use the onload attribute to remove the background image once the actual image has loaded.

Good to know
With server-side rendering (SSR), the image often loads before the JavaScript bundle has executed. This delays the triggering of the onload event, which can lead to a situation where both the placeholder and the actual image are visible at the same time. You can simulate a slow network in a production build with SSR to observe this effect.

Copy
---
import { Image, buildSrc } from '@imagekit/astro';

const placeholderUrl = buildSrc({
  src: "/default-image.jpg",
  transformation: [
    {
      quality: 10,
      blur: 90,
    },
  ],
});

const placeholderStyle = `background-image: url(${placeholderUrl}); background-size: cover; background-repeat: no-repeat; background-position: center;`;
---

<Image
  src="/default-image.jpg"
  alt="Image with placeholder"
  width={400}
  height={400}
  loading="lazy"
  style={placeholderStyle}
  onload="this.style.backgroundImage='none'"
/>

You can also extract this into a reusable component that wraps the Image component:

Copy
---
// src/components/ImageWithPlaceholder.astro
import { Image, buildSrc } from '@imagekit/astro';
import type { ImageProps } from '@imagekit/astro';

type Props = ImageProps & Partial<HTMLImageElement>;

const { src, urlEndpoint, transformation, onload: userOnload, style: userStyle, ...rest } = Astro.props;

const resolvedEndpoint = urlEndpoint ?? import.meta.env?.PUBLIC_IMAGEKIT_URL_ENDPOINT ?? import.meta.env?.IMAGEKIT_URL_ENDPOINT;

const placeholderUrl = buildSrc({
  urlEndpoint: resolvedEndpoint,
  src: src as string,
  transformation: [
    ...(transformation || []),
    { quality: 10, blur: 90 },
  ],
});

const placeholderStyle = `background-image: url(${placeholderUrl}); background-size: cover; background-repeat: no-repeat; background-position: center;`;
const combinedStyle = userStyle ? `${placeholderStyle} ${userStyle}` : placeholderStyle;

const clearPlaceholder = `this.style.backgroundImage='none';`;
const combinedOnload = userOnload
  ? `${clearPlaceholder} (${userOnload}).call(this, event);`
  : clearPlaceholder;
---

<Image
  src={src}
  urlEndpoint={urlEndpoint}
  transformation={transformation}
  {...rest}
  style={combinedStyle}
  onload={combinedOnload}
/>

Then use it in any page like a regular Image component:

Copy
---
import ImageWithPlaceholder from '../components/ImageWithPlaceholder.astro';
---

<ImageWithPlaceholder
  src="/default-image.jpg"
  alt="Image with placeholder"
  width={400}
  height={400}
  loading="lazy"
/>

Chained Transformations

You can chain multiple transformations by passing an array of transformation objects. Each object in the array creates a separate chained transformation step:

Copy
---
import { Image } from '@imagekit/astro';
---

<Image
  src="/photo.jpg"
  alt="Chained transformations"
  transformation={[
    { width: 400, height: 300 },  // First: resize
    { rotation: 90 },             // Then: rotate
  ]}
  width={400}
  height={300}
/>

Adding Overlays

You can add overlays to images and videos. The overlay can be text, image, video, subtitle, or solid color.

Image Overlay

Copy
<Image
  src="/background.jpg"
  alt="Background with image overlay"
  width={600}
  height={400}
  transformation={[
    { overlay: { type: "image", input: "logo.png" } }
  ]}
/>

With independent overlay transformations:

Copy
<Image
  src="/background.jpg"
  alt="Background with resized overlay"
  width={600}
  height={400}
  transformation={[
    {
      overlay: {
        type: "image",
        input: "logo.png",
        transformation: [{ width: 100, height: 100 }]
      }
    }
  ]}
/>

Text Overlay

Copy
<Image
  src="/background.jpg"
  alt="Background with text"
  width={600}
  height={400}
  transformation={[
    {
      overlay: {
        type: "text",
        text: "Hello, ImageKit!",
        transformation: [{ fontSize: 20, fontColor: "FF0000" }]
      }
    }
  ]}
/>

Solid Color Overlay

Copy
<Image
  src="/background.jpg"
  alt="Background with color overlay"
  width={600}
  height={400}
  transformation={[
    {
      overlay: {
        type: "solidColor",
        color: "FF0000",
        transformation: [{ width: 100, height: 100 }]
      }
    }
  ]}
/>

Video Overlay (on videos)

Copy
<Video
  src="/background.mp4"
  controls
  transformation={[
    {
      overlay: {
        type: "video",
        input: "overlay.mp4",
        timing: { start: 5, duration: 10 }
      }
    }
  ]}
/>

Subtitle Overlay (on videos)

Copy
<Video
  src="/background.mp4"
  controls
  transformation={[
    {
      overlay: {
        type: "subtitle",
        input: "subtitle.srt"
      }
    }
  ]}
/>

For more details on overlay options, positioning, encoding, and styling, see the overlay reference section.

Background Removal Using AI

Copy
<Image
  src="/photo.jpg"
  alt="Background removed"
  width={500}
  height={500}
  transformation={[{ aiRemoveBackground: true }]}
/>

ImageKit supports multiple AI-powered transformations including upscaling, drop shadow, generative fill, and more:

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

<!-- AI Upscale -->
<Image
  src="/small-photo.jpg"
  alt="Upscaled photo"
  width={500}
  height={500}
  transformation={[{ aiUpscale: true }]}
/>

Arithmetic Expressions

You can use arithmetic expressions to dynamically compute transformation values:

Copy
<Image
  src="/photo.jpg"
  alt="Half-width image"
  width={300}
  height={200}
  transformation={[{ width: "iw_div_2" }]}
/>

Check out the Arithmetic Expressions reference for more examples.

OG Image Meta Tags

The getOgImageTags() helper generates OpenGraph and Twitter Card meta tags with ImageKit-optimized image URLs. Use it in your page frontmatter and render the tags inside <head>.

Copy
---
import { getOgImageTags } from '@imagekit/astro/helpers';

const ogTags = getOgImageTags({
  src: '/og-banner.jpg',
  title: 'My Page Title',
  description: 'Preview description for social cards',
  alt: 'OG image description',
  twitterCard: 'summary_large_image',
  transformation: [{ width: 1200, height: 630 }],
});
---

<html>
<head>
  {ogTags.map((tag) => <meta {...tag} />)}
</head>
<body>...</body>
</html>

Generated Meta Tags

The helper generates the following tags (where applicable):

Copy
<meta property="og:title" content="..." />
<meta property="og:description" content="..." />
<meta property="og:image" content="..." />
<meta property="og:image:secure_url" content="..." />
<meta property="og:image:width" content="1200" />
<meta property="og:image:height" content="630" />
<meta property="og:image:alt" content="..." />
<meta property="twitter:title" content="..." />
<meta property="twitter:description" content="..." />
<meta property="twitter:card" content="summary_large_image" />
<meta property="twitter:image" content="..." />

Helper Options

Option Description
src (Required)Relative path or absolute ImageKit URL for the OG image.
titleShared title for both OG and Twitter tags. Can be overridden with ogTitle or twitterTitle.
ogTitle / twitterTitlePlatform-specific title overrides. Falls back to title.
descriptionShared description. Can be overridden with ogDescription or twitterDescription.
ogDescription / twitterDescriptionPlatform-specific description overrides. Falls back to description.
twitterCardTwitter card type. Default: summary_large_image. Options: summary, summary_large_image, app, player.
altAlt text for og:image:alt.
urlEndpointOverrides the environment variable for this call.
transformationArray of ImageKit transformations to apply to the OG image.
width / heightOG image dimensions. Default: 1200 × 630.
formatImage format override for the Twitter image. Default: webp.

Uploading Files

The Astro SDK exports a utility function, upload (re-exported from @imagekit/javascript), which enables you to upload files to ImageKit. This upload() function leverages the Upload V1 API, accepting an options object and returning a promise that resolves with the upload response.

The SDK automatically converts certain parameters into JSON strings, as required by the API. If a parameter is not explicitly supported by the SDK, it is included in the request as-is. For a complete list of parameters and expected formats, refer to the API documentation.

The SDK also provides a server-side helper, getUploadAuthParams, to generate the authentication parameters (signature, token, expire) needed for client-side file uploads. This function is exported from @imagekit/astro/server and should only be used in server-side code. For details on how to use this, see the generating authentication parameters section below.

upload() Parameters

The upload() function accepts a JSON object with the following parameters:

Option Description and Example
file
(Required)
The file content to be uploaded. Accepts binary data, a base64-encoded string, or a URL. Typically used with a File or Blob in the browser. Example: file: fileInput.files[0]
fileName
(Required)
The name to assign to the uploaded file. Supports alphanumeric characters, dot, underscore, and dash. Any other character is replaced with _. Example: fileName: "myImage.jpg"
signature
(Required)
The HMAC-SHA1 digest of the concatenation of "token + expire". The signing key is your ImageKit private API key. Must be computed on the server side. Example: signature: "generated_signature"

token
(Required)

A unique value to identify and prevent replays. Typically a UUID (e.g., version 4). Example: token: "unique_upload_token"

Check the generating authentication parameters section for more details on how to generate this value.

expire
(Required)

A Unix timestamp in seconds, less than 1 hour in the future. Example: expire: 1616161616

Check the generating authentication parameters section for more details on how to generate this value.

publicKey
(Required)

The public API key for your ImageKit account. This is used to identify the account making the upload request. Example: publicKey: "your_public_api_key"

Check the generating authentication parameters section for more details on how to generate this value.

onProgressA callback function to track the upload progress. It receives an event object with loaded and total properties. Example: onProgress: (event) => console.log(event.loaded, event.total) This is useful for showing upload progress to the user.
abortSignalAn optional AbortSignal object to abort the upload request. If the signal is already aborted, the upload will fail immediately. You can create an AbortController instance and pass its signal to the upload() function.
useUniqueFileNameBoolean flag to automatically generate a unique filename if set to true. Defaults to true. If false, the image is uploaded with the provided filename, replacing any existing file with the same name. Example: useUniqueFileName: true
folderThe folder path where the file will be stored, e.g., "/images/folder/". If the path doesn't exist, it is created on-the-fly. Example: folder: "/images/uploads"
isPrivateFileBoolean to mark the file as private, restricting access to the original file URL. A private file requires signed URLs or named transformations for access. Defaults to false. Example: isPrivateFile: false
tagsOptionally set tags on the uploaded file. Can be a comma-separated string or an array of tags. Example: tags: "summer,holiday" or tags: ["summer","holiday"]
customCoordinatesA string in "x,y,width,height" format that defines the region of interest in an image (top-left coords and area size). Example: customCoordinates: "10,10,100,100"
responseFieldsA comma-separated or array-based set of fields to return in the upload response. Example: responseFields: "tags,customCoordinates"
extensionsAn array of extension objects to apply to the image, e.g., background removal, auto-tagging, etc. Example: extensions: [{ name: "auto-tagging" }]
webhookUrlA webhook URL to receive the final status of any pending extensions once they've completed processing. Example: webhookUrl: "https://example.com/webhook"
overwriteFileDefaults to true. If false, and "useUniqueFileName" is also false, the API immediately fails if a file with the same name/folder already exists. Example: overwriteFile: true
overwriteAITagsDefaults to true. If true, and an existing file is found at the same location, its AITags are removed. Set to false to keep existing AITags. Example: overwriteAITags: true
overwriteTagsDefaults to true. If no tags are specified in the request, existing tags are removed from overwritten files. Setting to false has no effect if the request includes tags. Example: overwriteTags: true
overwriteCustomMetadataDefaults to true. If no customMetadata is specified in the request, existing customMetadata is removed from overwritten files. Setting to false has no effect if the request specifies customMetadata. Example: overwriteCustomMetadata: true
customMetadataA stringified JSON or an object containing custom metadata fields to store with the file. Custom metadata fields must be pre-defined in your ImageKit configuration. Example: customMetadata: {author: "John Doe"}
transformationDefines pre and post transformations to be applied to the file during upload. The SDK enforces certain validation rules for pre/post transformations. Example: transformation: { pre: "w-200,h-200", post: [...] }
checksA string specifying the checks to be performed server-side before uploading to the media library, e.g., size or mime type checks. Example: checks: "'file.size' < '1MB'"

Upload Example and Error Handling

The upload function expects the following mandatory parameters:

  • file and fileName – The file to be uploaded and the name you want to assign to it. The file value can be a File object, a base64-encoded string, or a URL.
  • Authentication parameterstoken, signature, expire, and publicKey.

Authentication is essential for secure file uploads from the browser. You should never expose your private API key in client-side code. Instead, generate these one-time authentication parameters on the server side and pass them to the client.

To simplify this process, the Astro SDK provides a server-side utility function: getUploadAuthParams. You can use this in an Astro API route to generate the required authentication parameters. It takes your private and public keys as input and returns the token, expire, and signature.

getUploadAuthParams must only be called on the server. Never expose your private key to the client.

Upload Flow Overview

Here's how the upload process using the SDK works:

  1. Client Request for Auth Parameters
    The client-side code calls an API endpoint to fetch the authentication parameters.
    You can implement your own application logic within this endpoint to authenticate the user.
    After that, use getUploadAuthParams to generate the upload credentials.

  2. File Upload
    Once the client has the auth parameters, it can call the upload function with the necessary data.

Generating Authentication Parameters

Add your ImageKit keys to .env:

Copy
IMAGEKIT_PRIVATE_KEY=your_private_key
IMAGEKIT_PUBLIC_KEY=your_public_key

Create a server-side API endpoint in Astro that returns auth parameters. Make sure to add an adapter to your Astro project and render the upload endpoint on demand.

In this endpoint, use the getUploadAuthParams function provided by @imagekit/astro/server to generate the required upload parameters.

This function takes your private and public keys and returns the token, expire, signature, and publicKey. You can also implement custom logic in this endpoint to ensure that only authenticated or authorized users can request upload credentials.

Copy
// src/pages/api/upload-auth.ts
import type { APIRoute } from 'astro';
import { getUploadAuthParams } from '@imagekit/astro/server';

export const prerender = false;

export const GET: APIRoute = async () => {
  // Your application logic to authenticate the user
  // For example, you can check if the user is logged in or has the necessary permissions
  // If the user is not authenticated, you can return an error response

  const authParams = getUploadAuthParams({
    privateKey: import.meta.env.IMAGEKIT_PRIVATE_KEY, // Never expose this on client side
    publicKey: import.meta.env.IMAGEKIT_PUBLIC_KEY,
    // expire: 30 * 60, // Optional, controls the expiry time of the token in seconds, maximum 1 hour in the future
    // token: "random-token", // Optional, a unique token for request
  });

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

getUploadAuthParams accepts these parameters:

Parameter Type Required Description
privateKeystringYesYour ImageKit private key.
publicKeystringYesYour ImageKit public key.
tokenstringNoCustom token. Auto-generated UUID if omitted.
expirenumberNoExpiry timestamp in seconds. Defaults to 30 minutes from now.

It returns an object with token, signature, expire, and publicKey.

Now your client-side code can call this API endpoint to retrieve the upload parameters.

The example below demonstrates how to use the upload function to upload a file, including error handling for various upload scenarios. You can copy and paste this code and customize it as needed.

Copy
---
// src/pages/upload.astro
---

<html>
<body>
  <input type="file" id="file-input" />
  <button id="upload-btn">Upload</button>
  <div>Upload progress: <progress id="upload-progress" value="0" max="100"></progress></div>
  <pre id="result"></pre>

  <script>
    import {
      upload,
      ImageKitAbortError,
      ImageKitInvalidRequestError,
      ImageKitServerError,
      ImageKitUploadNetworkError,
    } from '@imagekit/astro';

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

    // Create an AbortController instance to provide an option to cancel the upload if needed.
    const abortController = new AbortController();

    /**
     * Authenticates and retrieves the necessary upload credentials from the server.
     */
    const authenticator = async () => {
      const response = await fetch('/api/upload-auth');
      if (!response.ok) {
        const errorText = await response.text();
        throw new Error(`Request failed with status ${response.status}: ${errorText}`);
      }
      const data = await response.json();
      const { signature, expire, token, publicKey } = data;
      return { signature, expire, token, publicKey };
    };

    uploadBtn.addEventListener('click', async () => {
      const file = fileInput.files?.[0];
      if (!file) {
        alert('Please select a file to upload');
        return;
      }

      // Retrieve authentication parameters for the upload.
      let authParams;
      try {
        authParams = await authenticator();
      } catch (authError) {
        console.error('Failed to authenticate for upload:', authError);
        return;
      }
      const { signature, expire, token, publicKey } = authParams;

      try {
        const response = await upload({
          // Authentication parameters
          expire,
          token,
          signature,
          publicKey,
          file,
          fileName: file.name,
          // Progress callback to update upload progress
          onProgress: (event) => {
            progressBar.value = (event.loaded / event.total) * 100;
          },
          // Abort signal to allow cancellation of the upload if needed.
          abortSignal: abortController.signal,
        });
        console.log('Upload response:', response);
        result.textContent = JSON.stringify(response, null, 2);
      } catch (error) {
        // Handle specific error types provided by the ImageKit SDK.
        if (error instanceof ImageKitAbortError) {
          console.error('Upload aborted:', error.reason);
        } else if (error instanceof ImageKitInvalidRequestError) {
          console.error('Invalid request:', error.message);
        } else if (error instanceof ImageKitUploadNetworkError) {
          console.error('Network error:', error.message);
        } else if (error instanceof ImageKitServerError) {
          console.error('Server error:', error.message);
        } else {
          console.error('Upload error:', error);
        }
      }
    });
  </script>
</body>
</html>

Supported Transformations

The SDK assigns a name to each transformation parameter (e.g., height maps to h, width maps to w). If the property does not match any of the following supported options, it is added as-is in the URL.

If you want to generate transformations without any modifications, use the raw parameter. For example, SDK doesn't provide a nice way to write conditional transformations, so you can use the raw parameter to add them as-is.

Check transformation documentation for the complete reference on all transformations supported by ImageKit.

Transformation NameURL Parameter
widthw
heighth
aspectRatioar
qualityq
aiRemoveBackgrounde-bgremove (ImageKit powered)
aiRemoveBackgroundExternale-removedotbg (Using third party)
aiUpscalee-upscale
aiRetouche-retouch
aiVariatione-genvar
aiDropShadowe-dropshadow
aiChangeBackgrounde-changebg
cropc
cropModecm
xx
yy
xCenterxc
yCenteryc
focusfo
formatf
radiusr
backgroundbg
borderb
rotationrt
blurbl
namedn
dprdpr
progressivepr
losslesslo
trimt
metadatamd
colorProfilecp
defaultImagedi
originalorig
videoCodecvc
audioCodecac
grayscalee-grayscale
contrastStretche-contrast
shadowe-shadow
sharpene-sharpen
unsharpMaske-usm
gradiente-gradient
flipfl
opacityo
zoomz
pagepg
startOffsetso
endOffseteo
durationdu
streamingResolutionssr
overlayGenerates the correct layer syntax for image, video, text, subtitle, and solid color overlays.
rawThe string provided in raw will be added in the URL as-is.

Handling Unsupported Transformations

If you specify a transformation parameter that is not explicitly supported by the SDK, it is added as-is in the generated URL. This provides flexibility for using new or custom transformations without waiting for an SDK update. However, add @ts-ignore to avoid TypeScript errors, or use the raw parameter.

Copy
<Image
  src="/photo.jpg"
  alt="Custom transformation"
  width={500}
  height={500}
  transformation={[
    // @ts-ignore
    { unsupportedTransformation: "value" }
  ]}
/>

Or use the raw parameter:

Copy
<Image
  src="/photo.jpg"
  alt="Raw transformation"
  width={500}
  height={500}
  transformation={[
    { raw: "unsupportedTransformation-value" }
  ]}
/>

Overlay Reference

The SDK provides overlay as a transformation parameter. Overlays are applied using layers, allowing you to stack multiple overlays. Each overlay can be styled and positioned independently. For more details, refer to the layer documentation.

Option Description and Example
type (Required)Specifies the type of overlay. Supported values: text, image, video, subtitle, solidColor. Example: type: "text"
text (Required for text overlays)The text content to display. Example: text: "ImageKit"
input (Required for image, video, or subtitle overlays)Relative path to the overlay asset. Example: input: "logo.png"
color (Required for solidColor overlays)RGB/RGBA hex code or color name. Example: color: "FF0000"
encodingAccepted values: auto, plain, base64. Default: auto. The SDK determines the optimal encoding based on input content.
transformationAn array of transformation objects to style the overlay independently. Each overlay type has its own set of supported transformations — see below.
positionSets the overlay's position relative to the base asset. Accepts { x, y } or { focus: "center" }.
timing(Video base only) When the overlay appears: { start, duration, end } in seconds.

Encoding Options

Overlay encoding options define how the overlay input is converted for URL construction. When set to auto, the SDK automatically determines whether to use plain text or Base64 encoding based on the input content.

For text overlays:

  • If auto is used, the SDK checks the text overlay input: if it is URL-safe, it uses the format i-{input} (plain text); otherwise, it applies Base64 encoding with the format ie-{base64_encoded_input}.
  • You can force a specific method by setting encoding to plain (always use i-{input}) or base64 (always use ie-{base64}).
  • Note: In all cases, the text is percent-encoded to ensure URL safety.

For image, video, and subtitle overlays:

  • The input path is processed by removing any leading/trailing slashes and replacing inner slashes with @@ when plain is used.
  • Similarly, if auto is used, the SDK determines whether to apply plain text or Base64 encoding based on the characters present.
  • For explicit behavior, use plain or base64 to enforce the desired encoding.

Use auto for most cases to let the SDK optimize encoding, and use plain or base64 when a specific encoding method is required.

Solid Color Overlay Transformations

OptionDescriptionExample
widthWidth of the overlay block (pixels or arithmetic expression).width: 100
heightHeight of the overlay block.height: 50
radiusCorner radius. Number or "max" for circular/oval shapes.radius: "max"
alphaTransparency level, 1 (most transparent) to 9 (least transparent).alpha: 5
backgroundBackground color (RGB hex, RGBA, or color name).background: "red"
gradientCreates a linear gradient. Pass true for default or a string for custom.gradient: true

Text Overlay Transformations

OptionDescriptionExample
widthMaximum width of overlaid text (wraps automatically).width: 400
fontSizeFont size. Numeric value or arithmetic expression.fontSize: 50
fontFamilyFont family.fontFamily: "Arial"
fontColorFont color (RGB hex, RGBA, or color name).fontColor: "FF0000"
innerAlignmentText alignment: left, right, center.innerAlignment: "center"
paddingPadding around text.padding: 10
alphaTransparency level, 1–9.alpha: 5
typographyStyle: b (bold), i (italics), b_i (both).typography: "b"
backgroundBackground color of text overlay.background: "red"
radiusCorner radius of text overlay.radius: "max"
rotationRotation angle. Prefix N for counterclockwise.rotation: 90
flipFlip option: h, v, h_v, v_h.flip: "h"
lineHeightLine height for multi-line text.lineHeight: 20

Subtitle Overlay Transformations

OptionDescriptionExample
backgroundSubtitle background color.background: "blue"
fontSizeFont size.fontSize: 16
fontFamilyFont family.fontFamily: "Arial"
colorFont color.color: "FF0000"
typographyStyle: b, i, b_i.typography: "b"
fontOutlineOutline width and color, underscore-separated.fontOutline: "2_blue"
fontShadowShadow color and indent, underscore-separated.fontShadow: "blue_2"