To use Cloudinary with Astro, upload your images to Cloudinary and render them with transformation URLs such as https://res.cloudinary.com/<cloud>/image/upload/f_auto,q_auto,w_800/<public-id>, so Cloudinary resizes, compresses and picks the format on request instead of Astro doing it at build time. You can build those URLs in a small Astro component, use the community astro-cloudinary package for ready-made components, or plug Cloudinary into astro:assets as a custom image service. The Astro Cloudinary setup works on static sites, because the optimisation happens on Cloudinary’s CDN.
This guide covers all three routes, when each makes sense, and how to upload files to Cloudinary from an Astro Action.
Key Takeaways
- Cloudinary transforms images through URL parameters;
f_auto,q_autoalone picks the format and compression per browser.- A 30-line
CldImg.astrocomponent gives yousrcset,sizesand dimensions with no dependency.- Astro’s
<Image>would re-optimise Cloudinary files at build time; let Cloudinary do the work instead.- Keep the API secret on the server. Only the cloud name belongs in
PUBLIC_variables.- Use Cloudinary for large, editor-managed or user-uploaded libraries; local
astro:assetsis simpler for a handful of images.
When Cloudinary is worth adding to Astro
Astro’s built-in astro:assets already resizes and converts local images at build time. For a portfolio with 40 photos, that’s all you need. Cloudinary starts paying off when:
- The library is large. Thousands of images make build-time processing slow. Cloudinary transforms on first request and caches the result.
- Editors upload images through a CMS or a dashboard and shouldn’t need a rebuild to change a crop.
- Visitors upload files, such as avatars or listing photos, on a server-rendered site.
- You need transformations Astro doesn’t do, like face-aware cropping, background removal, overlays or video.
The image CDN comparison puts Cloudinary next to imgix, ImageKit and host-provided image services if you’re still choosing.
How Cloudinary URLs work
Every delivered image is a URL with transformations between /upload/ and the public ID:
https://res.cloudinary.com/demo/image/upload/f_auto,q_auto,c_fill,w_800,h_450,g_auto/samples/landscapes/nature-mountains
| Parameter | Meaning |
|---|---|
f_auto |
Serve AVIF, WebP or JPEG depending on what the browser accepts |
q_auto |
Choose a compression level automatically |
w_800, h_450 |
Target width and height in pixels |
c_fill |
Crop to fill the box exactly; c_limit only shrinks |
g_auto |
Pick the crop focus automatically, around faces or salient areas |
dpr_2.0 |
Scale for high-density screens |
Cloudinary generates each variant the first time it’s requested and serves it from its CDN after that. Your Astro build doesn’t download or process anything. See Cloudinary’s transformation reference for the full list.
Option 1: a dependency-free CldImg component
Most sites only need responsive <img> tags with a sensible srcset. That’s a short component:
---
// src/components/CldImg.astro
import type { HTMLAttributes } from 'astro/types';
interface Props extends Omit<HTMLAttributes<'img'>, 'src' | 'srcset' | 'width' | 'height'> {
src: string; // Cloudinary public ID, e.g. "blog/hero-desk"
alt: string;
width: number;
height: number;
widths?: number[];
crop?: 'fill' | 'limit';
}
const {
src,
alt,
width,
height,
widths = [400, 800, 1200, 1600],
crop = 'fill',
sizes = `(min-width: ${width}px) ${width}px, 100vw`,
loading = 'lazy',
...rest
} = Astro.props;
const cloud = import.meta.env.PUBLIC_CLOUDINARY_CLOUD_NAME;
const ratio = height / width;
const url = (w: number) => {
const h = Math.round(w * ratio);
const t = ['f_auto', 'q_auto', `c_${crop}`, `w_${w}`, crop === 'fill' ? `h_${h},g_auto` : ''];
return `https://res.cloudinary.com/${cloud}/image/upload/${t.filter(Boolean).join(',')}/${src}`;
};
const usable = widths.filter((w) => w <= width * 2);
---
<img
src={url(width)}
srcset={usable.map((w) => `${url(w)} ${w}w`).join(', ')}
sizes={sizes}
width={width}
height={height}
alt={alt}
loading={loading}
decoding="async"
{...rest}
/>
Use it anywhere, including MDX:
---
// src/pages/index.astro
import CldImg from '../components/CldImg.astro';
---
<CldImg src="blog/hero-desk" alt="A tidy desk with a laptop" width={1200} height={630} loading="eager" fetchpriority="high" />
<CldImg src="blog/team" alt="The team outside the office" width={800} height={533} />
The explicit width and height reserve space so the layout doesn’t shift while the image loads, and loading="eager" with fetchpriority="high" belongs on the image most likely to be your Largest Contentful Paint. Set PUBLIC_CLOUDINARY_CLOUD_NAME in .env. The cloud name appears in every URL anyway, so it’s fine to expose.
Option 2: the astro-cloudinary package
The community-maintained astro-cloudinary package (from the Cloudinary community, documented at astro.cloudinary.dev) gives you prebuilt components such as <CldImage> for images, <CldVideoPlayer> for video and an upload widget, plus a content loader that pulls assets from your Cloudinary account into a content collection.
npm install astro-cloudinary
---
// src/pages/gallery.astro
import { CldImage } from 'astro-cloudinary';
---
<CldImage src="samples/landscapes/nature-mountains" width="960" height="600" alt="Mountains at dusk" />
Choose the package if you want video, the upload widget or the collection loader without writing them yourself. Choose the small component if you only render images and prefer no extra dependency. Check the package’s docs for its current props and environment variable names, since community packages move faster than Astro core.
Option 3: Cloudinary as an Astro image service
Astro lets you replace the image service behind <Image> and <Picture>. An external service only has to turn options into a URL, so a Cloudinary service is short:
// src/image/cloudinary-service.ts
import type { ExternalImageService } from 'astro';
const cloud = import.meta.env.PUBLIC_CLOUDINARY_CLOUD_NAME;
const service: ExternalImageService = {
getURL(options) {
const src = typeof options.src === 'string' ? options.src : options.src.src;
const t = ['f_auto', options.quality ? `q_${options.quality}` : 'q_auto'];
if (options.width) t.push(`w_${options.width}`);
if (options.height) t.push(`h_${options.height}`, 'c_fill', 'g_auto');
return `https://res.cloudinary.com/${cloud}/image/upload/${t.join(',')}/${src}`;
},
};
export default service;
// astro.config.mjs
import { defineConfig } from 'astro/config';
export default defineConfig({
image: {
service: { entrypoint: './src/image/cloudinary-service.ts' },
},
});
Now <Image src="blog/team" width={800} height={533} alt="..." /> produces Cloudinary URLs, and you keep Astro’s attribute handling and widths/densities props. The catch is that the service applies to every image, including local imports, so this route suits sites where all images live in Cloudinary. The image services guide explains the service API, and the Image component guide covers the props.
A common mistake is to pass a full Cloudinary URL to Astro’s default <Image> and add res.cloudinary.com to image.domains. That works, but Astro downloads the file at build time and re-encodes it, which throws away Cloudinary’s on-demand formats and makes builds slower. Use one optimiser, not two.
Uploading to Cloudinary from an Astro Action
On a server-rendered site, you can accept uploads with an Astro Action and send them to Cloudinary with the official Node SDK:
npm install cloudinary
// astro.config.mjs (env schema excerpt)
import { defineConfig, envField } from 'astro/config';
export default defineConfig({
env: {
schema: {
CLOUDINARY_CLOUD_NAME: envField.string({ context: 'server', access: 'secret' }),
CLOUDINARY_API_KEY: envField.string({ context: 'server', access: 'secret' }),
CLOUDINARY_API_SECRET: envField.string({ context: 'server', access: 'secret' }),
},
},
});
// src/actions/index.ts
import { defineAction, ActionError } from 'astro:actions';
import { z } from 'astro/zod';
import { v2 as cloudinary } from 'cloudinary';
import { CLOUDINARY_CLOUD_NAME, CLOUDINARY_API_KEY, CLOUDINARY_API_SECRET } from 'astro:env/server';
cloudinary.config({
cloud_name: CLOUDINARY_CLOUD_NAME,
api_key: CLOUDINARY_API_KEY,
api_secret: CLOUDINARY_API_SECRET,
});
export const server = {
uploadAvatar: defineAction({
accept: 'form',
input: z.object({ file: z.instanceof(File) }),
handler: async ({ file }, context) => {
if (!context.locals.user) throw new ActionError({ code: 'UNAUTHORIZED' });
if (!file.type.startsWith('image/') || file.size > 5_000_000) {
throw new ActionError({ code: 'BAD_REQUEST', message: 'Upload an image under 5 MB.' });
}
const bytes = Buffer.from(await file.arrayBuffer());
const dataUri = `data:${file.type};base64,${bytes.toString('base64')}`;
const result = await cloudinary.uploader.upload(dataUri, {
folder: 'avatars',
public_id: context.locals.user.id,
overwrite: true,
});
return { publicId: result.public_id };
},
}),
};
The handler checks authentication, type and size before anything leaves your server, and the secret never reaches the browser. Store the returned publicId and render it with CldImg. Actions need an adapter, as covered in the Astro Actions guide. For large files or many uploads, Cloudinary’s signed direct uploads, where the browser sends the file to Cloudinary with a signature your server generates, avoid routing bytes through your function.
Cost, caching and limits
Cloudinary bills by credits that combine storage, transformations and bandwidth, and the free tier is enough for many small sites. Because each unique transformation counts, keep your widths list short and consistent across the site rather than generating arbitrary sizes. A fixed set like 400, 800, 1200 and 1600 pixels covers most layouts.
If you’d rather start from a layout that already handles image-heavy pages, the architecture and design themes are built around large galleries where an image CDN fits naturally.
FAQ
Does Astro have an official Cloudinary integration?
No. Astro core doesn’t include one. You can build transformation URLs yourself, use the community astro-cloudinary package, or write a small external image service that returns Cloudinary URLs for <Image> and <Picture>.
Should I use Astro’s Image component or Cloudinary?
Use Astro’s <Image> with local files for small, developer-managed image sets. Use Cloudinary when you have many images, editors or users upload them, or you need transformations like smart cropping. Avoid running both on the same image.
Can I use Cloudinary on a static Astro site?
Yes. Cloudinary transforms images on its CDN when the browser requests the URL, so a fully static Astro build with no adapter works. You only need a server for uploads that use your API secret.
Is the Cloudinary cloud name safe to expose?
Yes. The cloud name is part of every public image URL. Keep the API key and secret in server-only variables, for example with envField.string({ context: 'server', access: 'secret' }).
How do I make Cloudinary images responsive in Astro?
Generate a srcset with several w_ widths, add a sizes attribute that matches your layout, and set width and height so the browser reserves space. The CldImg component above does all three.