SvelteKit Image Optimizer is a utility designed for SvelteKit applications to handle image optimization at runtime.
It creates a dedicated endpoint within your SvelteKit application that processes and optimizes images on the fly using the powerful sharp library.
This approach is useful for images sourced externally, such as from a Content Management System (CMS), or any images not known at build time.
This library functions as a proxy, intercepting image requests, optimizing them based on defined parameters or browser capabilities, and then serving the processed image.
It is conceptually similar to services like Cloudflare’s image optimizer or the image optimization capabilities found in frameworks like Next.js (specifically next/image).
Features
⚡ On-the-Fly Optimization: Optimizes and resizes images dynamically as they are requested.
🔄 Automatic Format Conversion: Converts images to modern formats like WebP and AVIF based on browser Accept headers, ensuring optimal delivery.
🖼️ Responsive Images: Simplifies the creation of responsive images that adapt to different screen sizes using Image and Picture components.
💾 Flexible Caching: Supports multiple caching strategies including memory, filesystem, and S3-compatible storage, with options to create custom cache adapters.
🧩 Svelte Components: Provides easy-to-use <Image> and <Picture> components, along with a toOptimizedURL function for generating optimized image URLs.
🌐 External Image Support: Optimizes images from external domains, with security controls to allowlist specific domains.
🛡️ Serve External Images from Own Domain: Proxies external images through your domain, which can be beneficial for SEO.
⚙️ Customizable Output: Offers control over quality, image dimensions, fit, position, and background color during optimization.
🔗 Preloading: Supports preload and prefetch options to enhance loading performance for critical images.
🎞️ Animated Image Handling: Animated images (like GIFs) are piped through directly as sharp does not transform them.
🔧 Configurable Endpoint: Allows customization of the API route used for image optimization.
⏱️ Cache TTL Strategy: Provides control over cache Time-To-Live (TTL) based on source headers, immutable settings, or custom durations.
⚖️ Minimum Size Threshold: Optimizes images only if they exceed a certain file size (default 5kb).
Use Cases
- CMS-Driven Websites – Optimize images uploaded by content creators without manual intervention
- E-commerce Platforms – Automatically resize product images for different viewport sizes and device capabilities
- Blog Platforms – Handle user-uploaded images and external media with consistent optimization
- Portfolio Websites – Serve high-quality images while maintaining fast loading times across devices
- News Websites – Optimize images from wire services and external sources while serving from your domain
How To Use It
1. Install sveltekit-image-optimize and its peer dependency sharp.
npm i sveltekit-image-optimize sharp2. Add the image optimizer handler to your hooks.server.ts file.
// hooks.server.ts
import { createImageOptimizer } from 'sveltekit-image-optimize';
const imageHandler = createImageOptimizer({
// Optional: Configure caching, allowed domains, etc.
// cache: createMemoryCache(), // Example: using memory cache
}); // If you have multiple handlers, use SvelteKit's `sequence` utility
export const handle = imageHandler;3. Import and use the Image or Picture components, or the toOptimizedURL function.
<script lang="ts">
import { Image, Picture, toOptimizedURL } from 'sveltekit-image-optimize/components';
</script>
<!-- Basic Image Component -->
<Image
src="/path/to/your/local-image.jpg"
alt="Descriptive alt text"
width="600"
height="420"
optimizeOptions={{ preload: "prefetch" }}
/>
<!-- Picture Component for art direction -->
<Picture
src="https://external.com/remote-image.png"
alt="Responsive image"
sources={[
{
media: '(min-width: 1024px)',
optimizeOptions: { width: 800 }
},
{
media: '(min-width: 768px)',
optimizeOptions: { width: 600 }
}
]}
/>
<!-- Generating an optimized URL -->
<img src={toOptimizedURL("/another-image.webp", { width: 300, quality: 70 })} alt="Optimized via function" />4. If you change the default optimizer route (default is /api/image-op) in the createImageOptimizer options, you must initialize the client with the new route.
// hooks.client.ts
import { initImageOptimizerClient } from 'sveltekit-image-optimize/client';
import type { ClientInit } from '@sveltejs/kit';
export const init: ClientInit = () => {
initImageOptimizerClient({
route: '/my-custom-image-route' // Only if changed from default
});
};5. The library offers various caching adapters like createMemoryCache, createFileSystemCache, and createS3Cache. You can also implement your own custom cache adapter.
Related Resources
- Sharp Documentation – The high-performance image processing library powering this optimizer
- SvelteKit Documentation – Official guide for SvelteKit framework and server-side rendering
- Web.dev Image Optimization – Best practices for image optimization and Core Web Vitals
- AWS S3 SDK – Required for S3 cache adapter implementation
FAQs
Q: How is SvelteKit Image Optimizer different from @sveltejs/enhanced-img?
A: SvelteKit Image Optimizer handles image optimization at runtime (on-the-fly) for external images or images from CMSs. @sveltejs/enhanced-img performs image optimization at build time for local, static images.
Q: What image formats can be outputted?
A: The optimizer primarily uses sharp, which supports outputting to modern formats like WebP and AVIF, as well as standard formats like JPEG and PNG. The endpoint often selects the best format based on the browser’s Accept header unless a specific format is enforced.
Q: Can I optimize images from any external domain?
A: Yes, but for security, you should configure the allowedDomains option in the createImageOptimizer setup to specify which external domains are permitted for optimization.






