コンテンツにスキップ

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.

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, so the integration can be added to an existing project 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.

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

Terminal window
npm install @imagekit/astro

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

.env
IMAGEKIT_URL_ENDPOINT="https://ik.imagekit.io/<your_imagekit_id>"
# Only needed if you generate upload auth tokens on the server
PUBLIC_IMAGEKIT_PUBLIC_KEY="<Your Public Key>"
IMAGEKIT_PRIVATE_KEY="<Your Private Key>"

Then register the integration in astro.config.mjs:

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:

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

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.

Component.astro
---
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):

Component.astro
---
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.

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

Component.astro
---
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.

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.

Component.astro
---
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:

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

The @imagekit/video-player ships a dedicated Astro integration via the @imagekit/video-player/astro subpath export. This gives you a native IKVideoPlayer Astro component with full TypeScript types (IKPlayerOptions, SourceOptions). It works directly in .astro files without any framework adapter. It is built on Video.js and adds 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:

Terminal window
npm install @imagekit/video-player

Then use the IKVideoPlayer component in any .astro file:

VideoPlayer.astro
---
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.

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>.

Layout.astro
---
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:

Layout.astro
---
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.

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:

src/pages/api/upload-auth.ts
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:

Terminal window
npm install @imagekit/javascript

A minimal upload form on a .astro page:

src/pages/upload.astro
<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.

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:

Terminal window
npm install -D @imagekit/nodejs

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

src/content.config.ts
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:

src/pages/gallery.astro
---
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' }]}
/>
))}

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

src/pages/api/upload.ts
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',
});

その他のホスティングメディアガイド

貢献する コミュニティ スポンサー