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:
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:
// 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:
# 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-serviceimage.domains— allowsik.imagekit.ioand any hostname derived from yoururlEndpointimage.remotePatterns— adds secure (https) patterns for ImageKit hosts
You can also pass options directly to the integration:
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 |
|---|---|
| urlEndpoint | The ImageKit URL endpoint. If omitted, falls back to PUBLIC_IMAGEKIT_URL_ENDPOINT or IMAGEKIT_URL_ENDPOINT environment variables. |
| transformationPosition | Where to place transformations in the URL: "query" (default, ?tr=...) or "path" (/tr:.../). |
| domains | Additional hostnames to allow in Astro's image config. Merged with defaults. |
| remotePatterns | Additional 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:
// 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) | |
|---|---|---|
| Setup | One-line Astro integration | Manual image config |
| Auto-configures domains/patterns | Yes | No |
| Auto-sets image service | Yes | N/A (you set it yourself) |
| Flexibility | Good for most projects | Full 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 responsivesrc,srcSet, andsizesattributes.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
srcshould be a relative path (appended tourlEndpoint) or an absolute ImageKit URL. It does not accept statically imported image files.- If width is not provided, the image service attempts to infer dimensions automatically (requires Astro 4.12+). For best results, always provide explicit
widthandheight.
| Parameter | Description and Example |
|---|---|
urlEndpoint | The base URL endpoint from your ImageKit dashboard. If omitted, the value from Example: |
src | A relative or absolute path to the image.
Examples: |
transformation | An array of transformation objects. Each object can include properties like Example: See all supported transformation options. |
queryParameters | An object with additional query parameters to append to the URL. Example: |
| responsive | A 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. |
| transformationPosition | Specifies 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: |
imageBreakpoints | Custom image-specific breakpoints for responsive image generation. Default: |
Basic Usage
---
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:
---
import { Image } from '@imagekit/astro';
---
<Image
src="/default-image.jpg"
alt="A sample image"
width={400}
height={300}
/>
Image with Transformations
<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:
<!-- 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
- In the ImageKit dashboard, go to External Storage and click Add New.
- Choose Web proxy as the origin type.
- Save the origin and make sure it is enabled for your URL endpoint (default endpoint or a custom one via origin preference).
- 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):
<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:
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":
<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:
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:
<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.
---
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
<Video
src="/sample-video.mp4"
transformation={[{ width: 640, height: 360 }]}
width={640}
height={360}
controls
/>
Video with HTML Attributes
<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:
---
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:
---
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:
Using the priority Prop (Recommended, Astro 5.10+)
The priority prop (or shorthand priority) automatically optimizes an image for critical rendering by setting optimal values for loading, decoding, and fetch priority:
<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 deferringdecoding="sync"– synchronously decode to avoid rendering delayfetchpriority="high"– signal to the browser to prioritize this resource
Using Individual HTML Attributes
For more control, set loading attributes individually:
<!-- 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:
<!-- 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.
Default Responsive Behavior (Recommended)
When responsive is true (the default), the SDK automatically generates srcSet and sizes attributes using ImageKit's intelligent breakpoint system:
<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:
<!-- 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:
<!-- 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:
<!-- 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:
<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 variantsimageBreakpoints: Image-specific sizes, typically smaller for generating compact variants
Disabling Responsive Images
If you need manual control or have custom responsive handling:
<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:
- Explicit
srcset+sizesattribute – Takes precedence over all SDK-generated responsive behavior - Astro
densitiesprop – When provided, disables ImageKit responsive and uses Astro's density-based srcset - Astro
widths+sizesprops – 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. - Astro
layoutprop – 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. - ImageKit
responsive=true(default) – Automatically generates responsive srcset with intelligent breakpoints.
<!-- 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.
<!-- 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.
---
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:
---
// 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:
---
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:
---
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
<Image
src="/background.jpg"
alt="Background with image overlay"
width={600}
height={400}
transformation={[
{ overlay: { type: "image", input: "logo.png" } }
]}
/>
With independent overlay transformations:
<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
<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
<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)
<Video
src="/background.mp4"
controls
transformation={[
{
overlay: {
type: "video",
input: "overlay.mp4",
timing: { start: 5, duration: 10 }
}
}
]}
/>
Subtitle Overlay (on videos)
<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
<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:
<!-- 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:
<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>.
---
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):
<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. |
| title | Shared title for both OG and Twitter tags. Can be overridden with ogTitle or twitterTitle. |
| ogTitle / twitterTitle | Platform-specific title overrides. Falls back to title. |
| description | Shared description. Can be overridden with ogDescription or twitterDescription. |
| ogDescription / twitterDescription | Platform-specific description overrides. Falls back to description. |
| twitterCard | Twitter card type. Default: summary_large_image. Options: summary, summary_large_image, app, player. |
| alt | Alt text for og:image:alt. |
| urlEndpoint | Overrides the environment variable for this call. |
| transformation | Array of ImageKit transformations to apply to the OG image. |
| width / height | OG image dimensions. Default: 1200 × 630. |
| format | Image 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 | A unique value to identify and prevent replays. Typically a UUID (e.g., version 4). Example: Check the generating authentication parameters section for more details on how to generate this value. |
expire | A Unix timestamp in seconds, less than 1 hour in the future. Example: Check the generating authentication parameters section for more details on how to generate this value. |
publicKey | The public API key for your ImageKit account. This is used to identify the account making the upload request. Example: Check the generating authentication parameters section for more details on how to generate this value. |
| onProgress | A 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. |
| abortSignal | An 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. |
| useUniqueFileName | Boolean 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 |
| folder | The 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" |
| isPrivateFile | Boolean 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 |
| tags | Optionally 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"] |
| customCoordinates | A 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" |
| responseFields | A comma-separated or array-based set of fields to return in the upload response. Example: responseFields: "tags,customCoordinates" |
| extensions | An array of extension objects to apply to the image, e.g., background removal, auto-tagging, etc. Example: extensions: [{ name: "auto-tagging" }] |
| webhookUrl | A webhook URL to receive the final status of any pending extensions once they've completed processing. Example: webhookUrl: "https://example.com/webhook" |
| overwriteFile | Defaults 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 |
| overwriteAITags | Defaults 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 |
| overwriteTags | Defaults 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 |
| overwriteCustomMetadata | Defaults 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 |
| customMetadata | A 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"} |
| transformation | Defines 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: [...] } |
| checks | A 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:
fileandfileName– The file to be uploaded and the name you want to assign to it. Thefilevalue can be aFileobject, a base64-encoded string, or a URL.- Authentication parameters –
token,signature,expire, andpublicKey.
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:
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, usegetUploadAuthParamsto generate the upload credentials.File Upload
Once the client has the auth parameters, it can call theuploadfunction with the necessary data.
Generating Authentication Parameters
Add your ImageKit keys to .env:
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.
// 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 |
|---|---|---|---|
| privateKey | string | Yes | Your ImageKit private key. |
| publicKey | string | Yes | Your ImageKit public key. |
| token | string | No | Custom token. Auto-generated UUID if omitted. |
| expire | number | No | Expiry 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.
---
// 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 Name | URL Parameter |
|---|---|
| width | w |
| height | h |
| aspectRatio | ar |
| quality | q |
| aiRemoveBackground | e-bgremove (ImageKit powered) |
| aiRemoveBackgroundExternal | e-removedotbg (Using third party) |
| aiUpscale | e-upscale |
| aiRetouch | e-retouch |
| aiVariation | e-genvar |
| aiDropShadow | e-dropshadow |
| aiChangeBackground | e-changebg |
| crop | c |
| cropMode | cm |
| x | x |
| y | y |
| xCenter | xc |
| yCenter | yc |
| focus | fo |
| format | f |
| radius | r |
| background | bg |
| border | b |
| rotation | rt |
| blur | bl |
| named | n |
| dpr | dpr |
| progressive | pr |
| lossless | lo |
| trim | t |
| metadata | md |
| colorProfile | cp |
| defaultImage | di |
| original | orig |
| videoCodec | vc |
| audioCodec | ac |
| grayscale | e-grayscale |
| contrastStretch | e-contrast |
| shadow | e-shadow |
| sharpen | e-sharpen |
| unsharpMask | e-usm |
| gradient | e-gradient |
| flip | fl |
| opacity | o |
| zoom | z |
| page | pg |
| startOffset | so |
| endOffset | eo |
| duration | du |
| streamingResolutions | sr |
| overlay | Generates the correct layer syntax for image, video, text, subtitle, and solid color overlays. |
| raw | The 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.
<Image
src="/photo.jpg"
alt="Custom transformation"
width={500}
height={500}
transformation={[
// @ts-ignore
{ unsupportedTransformation: "value" }
]}
/>
Or use the raw parameter:
<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" |
| encoding | Accepted values: auto, plain, base64. Default: auto. The SDK determines the optimal encoding based on input content. |
| transformation | An array of transformation objects to style the overlay independently. Each overlay type has its own set of supported transformations — see below. |
| position | Sets 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
autois used, the SDK checks the text overlay input: if it is URL-safe, it uses the formati-{input}(plain text); otherwise, it applies Base64 encoding with the formatie-{base64_encoded_input}. - You can force a specific method by setting encoding to
plain(always usei-{input}) orbase64(always useie-{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
@@whenplainis used. - Similarly, if
autois used, the SDK determines whether to apply plain text or Base64 encoding based on the characters present. - For explicit behavior, use
plainorbase64to 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
| Option | Description | Example |
|---|---|---|
| width | Width of the overlay block (pixels or arithmetic expression). | width: 100 |
| height | Height of the overlay block. | height: 50 |
| radius | Corner radius. Number or "max" for circular/oval shapes. | radius: "max" |
| alpha | Transparency level, 1 (most transparent) to 9 (least transparent). | alpha: 5 |
| background | Background color (RGB hex, RGBA, or color name). | background: "red" |
| gradient | Creates a linear gradient. Pass true for default or a string for custom. | gradient: true |
Text Overlay Transformations
| Option | Description | Example |
|---|---|---|
| width | Maximum width of overlaid text (wraps automatically). | width: 400 |
| fontSize | Font size. Numeric value or arithmetic expression. | fontSize: 50 |
| fontFamily | Font family. | fontFamily: "Arial" |
| fontColor | Font color (RGB hex, RGBA, or color name). | fontColor: "FF0000" |
| innerAlignment | Text alignment: left, right, center. | innerAlignment: "center" |
| padding | Padding around text. | padding: 10 |
| alpha | Transparency level, 1–9. | alpha: 5 |
| typography | Style: b (bold), i (italics), b_i (both). | typography: "b" |
| background | Background color of text overlay. | background: "red" |
| radius | Corner radius of text overlay. | radius: "max" |
| rotation | Rotation angle. Prefix N for counterclockwise. | rotation: 90 |
| flip | Flip option: h, v, h_v, v_h. | flip: "h" |
| lineHeight | Line height for multi-line text. | lineHeight: 20 |
Subtitle Overlay Transformations
| Option | Description | Example |
|---|---|---|
| background | Subtitle background color. | background: "blue" |
| fontSize | Font size. | fontSize: 16 |
| fontFamily | Font family. | fontFamily: "Arial" |
| color | Font color. | color: "FF0000" |
| typography | Style: b, i, b_i. | typography: "b" |
| fontOutline | Outline width and color, underscore-separated. | fontOutline: "2_blue" |
| fontShadow | Shadow color and indent, underscore-separated. | fontShadow: "blue_2" |