ImageKit & Astro
此内容尚不支持你的语言。
ImageKit is a real-time media optimization and delivery platform with a global CDN, a built-in Digital Asset Manager (DAM), and a URL-based transformation API for images and videos.
When delivering through ImageKit, you get automatic format conversion (AVIF, WebP), automatic quality, responsive images, AI-powered transformations (background removal, generative fill, upscaling), and adaptive video streaming.
Using ImageKit in Astro
Section titled “Using ImageKit in Astro”The ImageKit Astro SDK registers a custom image service that re-routes Astro’s built-in <Image /> and <Picture /> components, plus Markdown and MDX images, through ImageKit. Local imports continue to be processed by Astro’s built-in Sharp service. This means an existing project can add the integration without breaking existing assets.
The SDK also provides a <Video /> component, an <OgImage /> component for social cards, and a server-side helper for issuing client-side upload tokens.
For pure URL building or browser uploads in any framework, you can also use the lower-level ImageKit JavaScript SDK. For server-side asset management (uploading, listing, deleting, metadata), use the ImageKit Node.js SDK.
Prerequisites
Section titled “Prerequisites”- An existing Astro project
- An ImageKit account
Installing the ImageKit Astro SDK
Section titled “Installing the ImageKit Astro SDK”Install the SDK by running the appropriate command for your package manager:
npm install @imagekit/astropnpm add @imagekit/astroyarn add @imagekit/astroConfiguring your account
Section titled “Configuring your account”Create a new .env file in the root of your project and add your ImageKit credentials:
IMAGEKIT_URL_ENDPOINT="https://ik.imagekit.io/<your_imagekit_id>"
# Only needed if you generate upload auth tokens on the serverPUBLIC_IMAGEKIT_PUBLIC_KEY="<Your Public Key>"IMAGEKIT_PRIVATE_KEY="<Your Private Key>"Then register the integration in astro.config.mjs:
import { defineConfig } from 'astro/config';import imagekit from '@imagekit/astro/integration';
export default defineConfig({ integrations: [imagekit()],});You can also pass urlEndpoint directly to the integration instead of using the environment variable:
imagekit({ urlEndpoint: 'https://ik.imagekit.io/<your_imagekit_id>',}),Using ImageKit images
Section titled “Using ImageKit images”With the integration installed, Astro’s built-in <Image /> and <Picture /> components route requests through ImageKit and apply automatic format and quality optimization, responsive srcset, and lazy loading.
---import { Image } from 'astro:assets';---<Image src="/sample.jpg" width={800} height={600} alt="A sample image"/>The integration adds an additional transformation prop on <Image />, <Picture />, and getImage() for applying any ImageKit transformation (e.g. cropping, focus, AI effects, overlays):
---import { Image } from 'astro:assets';---<Image src="/portrait.jpg" width={500} height={500} alt="Cropped portrait" transformation={[{ width: 500, height: 500, focus: 'face' }]}/>The component-level width and height set the rendered HTML dimensions. The values inside transformation control the ImageKit server-side resize.
AI-powered transformations
Section titled “AI-powered transformations”ImageKit transformations include AI effects that can be applied through the same transformation prop:
---import { Image } from 'astro:assets';---<!-- Remove background --><Image src="/product.jpg" width={500} height={500} alt="Product with background removed" transformation={[{ aiRemoveBackground: true }]}/>
<!-- Upscale a low-resolution image --><Image src="/thumbnail.jpg" width={1024} height={1024} alt="Upscaled image" transformation={[{ aiUpscale: true }]}/>
<!-- Generative fill to extend an image to a new aspect ratio --><Image src="/portrait.jpg" width={1600} height={900} alt="Image extended with generative fill" transformation={[ { width: 1600, height: 900, cropMode: 'pad_resize', background: 'genfill' }, ]}/>
<!-- AI drop shadow --><Image src="/product.png" width={500} height={500} alt="Product with AI drop shadow" transformation={[{ aiDropShadow: true }]}/>See the supported transformations reference in ImageKit documentation for the full list, including overlays, smart cropping (focus: 'auto', focus: 'face'), and other effects.
Using ImageKit videos
Section titled “Using ImageKit videos”Add videos to your .astro components with the <Video /> component. It accepts standard HTML video attributes alongside ImageKit-specific props such as transformation and urlEndpoint.
---import { Video } from '@imagekit/astro';---<Video src="/sample.mp4" width={1280} height={720} controls/>To resize the video on ImageKit’s side, pass dimensions inside transformation:
<Video src="/sample.mp4" width={640} height={360} transformation={[{ width: 640, height: 360 }]} controls/>ImageKit Video Player
Section titled “ImageKit Video Player”The @imagekit/video-player package exports a dedicated Astro integration through the @imagekit/video-player/astro subpath. It provides a native IKVideoPlayer Astro component with full TypeScript types (IKPlayerOptions, SourceOptions). You can use it directly in .astro files without any framework adapter.
The player is built on Video.js and includes AI-generated subtitles and chapters, automatic translation into 50+ languages, word-level karaoke-style highlighting, seek thumbnails, a floating sticky player, and adaptive bitrate streaming (HLS/DASH). No manual transcription work is required.
Install the package:
npm install @imagekit/video-playerpnpm add @imagekit/video-playeryarn add @imagekit/video-playerThen use the IKVideoPlayer component in any .astro file:
---import { IKVideoPlayer } from '@imagekit/video-player/astro';import '@imagekit/video-player/styles.css';
const ikOptions = { imagekitId: 'YOUR_IMAGEKIT_ID', seekThumbnails: true,};
const source = { src: 'https://ik.imagekit.io/your_imagekit_id/video.mp4', chapters: true, // AI-generated chapter markers textTracks: [{ autoGenerate: true, // AI speech-to-text subtitles default: true, highlightWords: true, // word-level highlighting translations: [ { langCode: 'es', label: 'Spanish' }, { langCode: 'fr', label: 'French' }, ], }],};---
<IKVideoPlayer ikOptions={ikOptions} source={source} />With chapters: true, the player auto-generates chapter markers from the video content. Setting autoGenerate: true in textTracks creates AI speech-to-text subtitles without any .srt files. Each entry in translations adds an automatically generated subtitle track in that language.
The Video Player SDK is currently in beta. Test thoroughly before using it in production. See the Video Player overview in ImageKit documentation for the full list of options, including playlists, shoppable videos, and signed URL support.
Generating Open Graph image URLs
Section titled “Generating Open Graph image URLs”Use the <OgImage /> component to render OpenGraph and Twitter Card <meta> tags pointing at an ImageKit-optimized image. Place it inside your layout’s <head>.
---import { OgImage } from '@imagekit/astro';---<html> <head> <OgImage src="/og-banner.jpg" title="My page title" description="Preview description for social cards" alt="OG image description" /> </head> <body><slot /></body></html>If you need just a URL instead of the rendered tags, use the getOgImageUrl() helper:
---import { getOgImageUrl } from '@imagekit/astro';
const ogImage = getOgImageUrl({ src: '/og-banner.jpg', transformation: [{ width: 1200, height: 630 }],});---<meta property="og:image" content={ogImage} />See the ImageKit OG component documentation for a complete list of supported props.
Enabling client-side uploads
Section titled “Enabling client-side uploads”To upload files directly from the browser, generate a short-lived authentication token on the server using the getUploadAuthParams() helper from @imagekit/astro/server. The private key stays server-side and is never sent to the browser.
This requires an adapter so the endpoint runs on demand:
import type { APIRoute } from 'astro';import { getUploadAuthParams } from '@imagekit/astro/server';
export const prerender = false; // Not needed in 'server' mode
export const GET: APIRoute = () => { const authParams = getUploadAuthParams({ privateKey: import.meta.env.IMAGEKIT_PRIVATE_KEY, publicKey: import.meta.env.PUBLIC_IMAGEKIT_PUBLIC_KEY, });
return new Response(JSON.stringify(authParams), { headers: { 'Content-Type': 'application/json' }, });};The browser then fetches this endpoint and passes the returned signature, token, expire, and publicKey to the upload() function from @imagekit/javascript. Install it as a direct dependency:
npm install @imagekit/javascriptpnpm add @imagekit/javascriptyarn add @imagekit/javascriptA minimal upload form on a .astro page:
<input type="file" id="file-input" /><button id="upload-btn">Upload</button><progress id="upload-progress" value="0" max="100"></progress>
<script> import { upload } from '@imagekit/javascript';
const fileInput = document.getElementById('file-input') as HTMLInputElement; const uploadBtn = document.getElementById('upload-btn') as HTMLButtonElement; const progress = document.getElementById('upload-progress') as HTMLProgressElement;
uploadBtn.addEventListener('click', async () => { const file = fileInput.files?.[0]; if (!file) return;
const auth = await fetch('/api/upload-auth').then((r) => r.json());
const result = await upload({ ...auth, file, fileName: file.name, onProgress: (e) => { progress.value = (e.loaded / e.total) * 100; }, });
console.log('Uploaded:', result); });</script>See the ImageKit guide for full error handling and abort signals.
Loading from your ImageKit Media Library
Section titled “Loading from your ImageKit Media Library”You can use Astro Content Collections together with the @imagekit/nodejs SDK to power gallery and listing pages directly from your ImageKit Media Library.
Install the Node SDK as a dev dependency:
npm install -D @imagekit/nodejspnpm add -D @imagekit/nodejsyarn add -D @imagekit/nodejsThen define a collection backed by client.assets.list(). The Node SDK returns an array of File | Folder objects. To limit results to images, pass type: 'file' to exclude folders and fileType: 'image'. Use the Files.File type guard so each entry is correctly typed before mapping it into your collection schema:
import { defineCollection } from 'astro:content';import { z } from 'astro/zod';import ImageKit from '@imagekit/nodejs';import type { Files } from '@imagekit/nodejs/resources/files/files';
const client = new ImageKit({ privateKey: import.meta.env.IMAGEKIT_PRIVATE_KEY,});
const gallery = defineCollection({ loader: async () => { const assets = await client.assets.list({ type: 'file', // exclude folders fileType: 'image', // only image files skip: 0, limit: 50, });
return assets .filter((asset): asset is Files.File => asset.type === 'file' && !!asset.fileId && !!asset.url ) .map((asset) => ({ id: asset.fileId ?? '', url: asset.url ?? '', width: asset.width ?? 0, height: asset.height ?? 0, name: asset.name ?? '', tags: asset.tags ?? [], })); }, schema: z.object({ url: z.string().url(), width: z.number(), height: z.number(), name: z.string(), tags: z.array(z.string()), }),});
export const collections = { gallery };After adding the collection, run astro sync (or start the dev server) to generate the collection types used by getCollection().
Render the collection with <Image> from astro:assets. The integration generates the ImageKit CDN URL with the requested transformations:
---import { Image } from 'astro:assets';import { getCollection } from 'astro:content';
const photos = await getCollection('gallery');---{photos.map(({ data }) => ( <Image src={data.url} width={data.width} height={data.height} alt={data.name} transformation={[{ width: 400, height: 300, focus: 'auto' }]} />))}Using ImageKit in Node.js
Section titled “Using ImageKit in Node.js”For server-side workflows such as bulk uploads, listing assets, or deleting files, use the official @imagekit/nodejs SDK directly:
import ImageKit from '@imagekit/nodejs';
const client = new ImageKit({ privateKey: import.meta.env.IMAGEKIT_PRIVATE_KEY,});
await client.files.upload({ file: '<file path, buffer, or URL>', fileName: 'sample.jpg',});Official resources
Section titled “Official resources”- ImageKit Astro SDK
- ImageKit Astro integration documentation
- ImageKit JavaScript SDK
- ImageKit Node.js SDK
- ImageKit transformation reference