
Images are often among the largest assets on a website. If your application contains hundreds or thousands of JPEG and PNG files, those images can increase page load times, consume bandwidth, and negatively affect the user experience.
Modern image formats such as AVIF and WebP can reduce file sizes while maintaining good visual quality. Migrating legacy images to these formats can improve loading performance, reduce storage requirements, and help deliver a faster website.
In this guide, you'll learn how to migrate existing images to WebP and AVIF using Node.js, automate batch conversion, maintain backward compatibility, and deploy the new assets safely.
1. Why Migrate Legacy Images?
Traditional formats such as JPEG and PNG remain useful, but they aren't always the most efficient choices for websites.
For example, a large photographic JPEG might be several hundred kilobytes. A carefully optimized WebP or AVIF version may deliver similar visual quality at a smaller size.
Benefits include:
Reduced image download sizes
Lower bandwidth consumption
Faster image loading on supported browsers
Potential improvements to Core Web Vitals
Reduced storage and image delivery costs
Actual savings depend on image content, dimensions, compression settings, and quality requirements. Always compare the output visually before replacing production assets.
2. Understanding WebP vs. AVIF
Before migrating your image library, it's important to understand the differences between the two formats.
WebP
WebP supports lossy and lossless compression, transparency, and animation.
It offers broad support in modern browsers and is often a practical default for general website images.
AVIF
AVIF is based on the AV1 image format and supports efficient lossy and lossless compression, transparency, and high dynamic range features.
It can produce smaller files than WebP for some images at comparable visual quality, although encoding may take longer.
Feature | WebP | AVIF |
|---|---|---|
Lossy compression | Yes | Yes |
Lossless compression | Yes | Yes |
Transparency | Yes | Yes |
Animation | Yes | Yes |
Browser support | Broad modern-browser support | Broad modern-browser support, but verify target environments |
Encoding speed | Generally faster | Can be slower |
File size | Often smaller than legacy formats | Often smaller than WebP, depending on the image |
Neither format wins for every image. Test both using representative assets from your own application.
3. Audit Your Existing Image Library
Start by identifying which images need conversion.
Typical legacy assets include:
.jpgand.jpegphotographs.pngillustrations and screenshotsLarge product images
Blog featured images
Hero banners
Images uploaded by users
Before converting anything, back up the original assets and record their dimensions, file sizes, and formats.
You can use the following command on Linux or macOS to locate common image files:
find public/images -type f \
\( -iname "*.jpg" -o -iname "*.jpeg" -o -iname "*.png" \)For a large project, build an inventory containing each image's original path, size, dimensions, and intended output format.
This makes it easier to review conversion results and roll back individual files if necessary.
4. Install Sharp in Node.js
Sharp is a popular Node.js image-processing library powered by libvips.
It supports common image transformations, including resizing, compression, and conversion to WebP and AVIF.
Install it in your project:
npm install sharpYou can use Sharp in a Node.js backend, build script, or image-processing worker.
For large image libraries, use a batch script rather than loading every image into memory simultaneously.
5. Convert JPEG and PNG Images to WebP
Create a file named convert-to-webp.js:
import sharp from "sharp";
import fs from "node:fs/promises";
import path from "node:path";
const inputDir = "public/images";
const outputDir = "public/optimized/webp";
await fs.mkdir(outputDir, { recursive: true });
const files = await fs.readdir(inputDir);
for (const file of files) {
if (!/\.(jpe?g|png)$/i.test(file)) {
continue;
}
const inputPath = path.join(inputDir, file);
const outputName = file.replace(/\.(jpe?g|png)$/i, ".webp");
const outputPath = path.join(outputDir, outputName);
try {
await sharp(inputPath)
.webp({ quality: 80, effort: 4 })
.toFile(outputPath);
console.log(`Converted: ${file} -> ${outputName}`);
} catch (error) {
console.error(`Failed to convert ${file}:`, error.message);
}
}Run the script:
node convert-to-webp.jsThis example converts supported JPEG and PNG files into a separate WebP directory.
The quality value of 80 is a starting point, not a universal setting. Photographs, screenshots, illustrations, and transparent graphics may require different settings.
The script intentionally preserves the originals, allowing you to compare results before updating your application.
Important: This basic example processes files in one directory. For nested folders, recursive traversal is required. Also, use a collision-safe naming strategy if different input files could produce the same output filename.
6. Convert Images to AVIF
You can also generate AVIF versions using Sharp.
Create convert-to-avif.js:
import sharp from "sharp";
import fs from "node:fs/promises";
import path from "node:path";
const inputDir = "public/images";
const outputDir = "public/optimized/avif";
await fs.mkdir(outputDir, { recursive: true });
const files = await fs.readdir(inputDir);
for (const file of files) {
if (!/\.(jpe?g|png)$/i.test(file)) {
continue;
}
const inputPath = path.join(inputDir, file);
const outputName = file.replace(/\.(jpe?g|png)$/i, ".avif");
const outputPath = path.join(outputDir, outputName);
try {
await sharp(inputPath)
.avif({ quality: 50, effort: 4 })
.toFile(outputPath);
console.log(`Converted: ${file} -> ${outputName}`);
} catch (error) {
console.error(`Failed to convert ${file}:`, error.message);
}
}Run it:
node convert-to-avif.jsAVIF's quality scale differs from WebP's, so don't assume that the same numerical quality value produces equivalent visual results.
Compare output file sizes and inspect image details before choosing final encoding settings.
For very large libraries, add controlled concurrency, progress reporting, and retry handling to avoid overwhelming server resources.
7. Serve Modern Formats with HTML
Once your optimized assets are ready, you can serve AVIF and WebP while keeping a JPEG or PNG fallback.
Use the HTML <picture> element:
<picture>
<source
srcset="/optimized/avif/product.avif"
type="image/avif"
/>
<source
srcset="/optimized/webp/product.webp"
type="image/webp"
/>
<img
src="/images/product.jpg"
alt="Product displayed on a table"
width="800"
height="600"
loading="lazy"
/>
</picture>The browser selects the first supported source. If neither modern format is supported, it falls back to the JPEG.
Replace the example paths with the actual URLs generated by your application.
For above-the-fold hero images, avoid lazy loading when it would delay the main visual content. Consider prioritizing the genuine Largest Contentful Paint (LCP) image instead.
8. Handle Responsive Images
Different devices need different image dimensions. Serving a large desktop image to a mobile phone can waste bandwidth even if the image uses AVIF or WebP.
Use responsive image sources:
<picture>
<source
type="image/avif"
srcset="
/images/hero-640.avif 640w,
/images/hero-1280.avif 1280w
"
sizes="(max-width: 768px) 100vw, 1200px"
/>
<source
type="image/webp"
srcset="
/images/hero-640.webp 640w,
/images/hero-1280.webp 1280w
"
sizes="(max-width: 768px) 100vw, 1200px"
/>
<img
src="/images/hero-1280.jpg"
alt="A developer working on a laptop"
width="1280"
height="720"
/>
</picture>Generate each referenced image variant before deploying this markup. The browser can then choose an appropriate source based on the device and layout.
9. Plan a Safe Production Migration
Avoid replacing every original image immediately. A staged migration is easier to test and reverse.
Step 1: Back up originals. Store an untouched copy of the original files.
Step 2: Convert a sample. Test representative photographs, transparent PNGs, screenshots, and thumbnails.
Step 3: Compare quality and size. Measure file-size savings and inspect visual artifacts.
Step 4: Generate variants. Create AVIF, WebP, and fallback files where required.
Step 5: Update application references. Change templates, components, or a centralized image service to use the new assets.
Step 6: Test before release. Verify image loading, transparency, responsive behavior, caching, and fallback support.
Step 7: Monitor performance. Compare actual image transfer sizes, loading behavior, and Core Web Vitals.
Keep the old files available until the new assets have been validated in production.
10. Common Mistakes to Avoid
Using excessive compression: Smaller files aren't worth visible artifacts.
Ignoring dimensions: A 3000-pixel image is often unnecessary for a small thumbnail.
Removing fallbacks too early: Some environments may require alternative formats.
Forgetting transparency: Check logos and illustrations carefully when converting PNG files.
Ignoring caching: Versioned filenames and correct cache headers help prevent stale images.
Converting on every request: Pre-generate static assets or use a controlled image-processing cache.
Ignoring animated images: A basic conversion script may not preserve animation as expected.
Overlooking licensing and metadata: Validate how metadata, orientation, and color profiles are handled by your processing pipeline.
Conclusion
Migrating legacy images to AVIF and WebP is a practical way to improve image delivery on modern websites.
With Sharp and Node.js, developers can automate conversion, preserve original assets, and generate responsive variants. The <picture> element makes it possible to deliver modern formats while maintaining fallbacks.
Start with an image audit, test a representative sample, and roll out the migration gradually. Measure actual file-size reductions and user-facing performance instead of assuming that a newer format will always produce a better result.
A thoughtful image migration can reduce bandwidth, improve loading experiences, and make your website more efficient without requiring a complete application rewrite.
Technical author and software engineer at DevByte. Writing deep-dive tutorials on distributed systems, modern full-stack web architectures, and cloud deployments.


