# What Is JPEG XL (JXL)? Compression, Browser Support and Adoption

> JPEG XL (.jxl) explained: lossless JPEG recompression that cut our test file by 15%, how it compares with AVIF and WebP, and Chrome 155 support.

Canonical page: https://www.imageguide.dev/guides/jpeg-xl-future-format/

Published: 2026-01-19. Updated: 2026-10-17.

Publisher: ImageGuide, published by Sirv. [Editorial method](https://www.imageguide.dev/about/#how-we-write).

## Quick answer

JPEG XL (JXL, .jxl files) is an image format for lossy and lossless images, HDR, transparency, and animation. Its unique feature is lossless JPEG recompression: in our test, cjxl in lossless JPEG mode cut a 125 KB JPEG to 106 KB, and djxl restored the original byte for byte. Chrome decodes JPEG XL from version 155 and Safari from version 17. Keep a JPEG, WebP, or AVIF fallback for other clients.

Reference for this answer: [MDN image format reference](https://developer.mozilla.org/en-US/docs/Web/Media/Guides/Formats/Image_types).

JPEG XL (JXL) represents the most ambitious attempt to create a universal image format. With superior compression, HDR support, and the unique ability to losslessly transcode existing JPEGs, it promises to be the future of web images — once browser support catches up. Whether you are evaluating the jxl format for a new project or planning a long-term migration, this guide covers everything from encoding workflows to server configuration.

## The Two Numbers That Make the Case

JPEG XL's headline claim is better compression. Its more interesting claim is that it can absorb your existing JPEG library without touching a pixel. Both are measurable.

**Lossless JPEG recompression.** `cjxl --lossless_jpeg=1` repacks an existing JPEG in JXL's container. No re-encoding, no generation loss, and `djxl` restores the original file byte for byte:

[View the interactive chart on the canonical page](https://www.imageguide.dev/guides/jpeg-xl-future-format/).

That is **15% off an entire JPEG archive** at zero quality cost, and the round trip verified as byte-identical. For a media library measured in terabytes, that is the whole business case, independent of browser support.

**The quality ladder.** JXL uses a distance parameter rather than a quality percentage, where `-d 1` means visually lossless and higher numbers allow more loss:

[View the interactive chart on the canonical page](https://www.imageguide.dev/guides/jpeg-xl-future-format/).

At `-d 1` the JXL landed at 127 KB against the JPEG's 125 KB — no better at all. The gain arrives further down the curve: `-d 2` reached 83 KB, a third smaller than the JPEG and still visually clean. Encoding at `-d 1` out of caution is the most common way to conclude that JXL does not help.

## What is JPEG XL?

JPEG XL is a royalty-free image format developed by the Joint Photographic Experts Group (the same organization behind the original JPEG standard). It was formally standardized as ISO/IEC 18181 in 2022 with the ambitious goal of replacing both JPEG and PNG as the dominant image formats on the web and beyond.

The format emerged from the merger of two research proposals: Google's PIK and Cloudinary's FUIF. That dual heritage gives jpeg xl an unusually broad feature set — it handles photographic content, synthetic graphics, animations, and lossless archival with a single codec. Unlike formats that optimize for one niche, the jxl format was designed from the ground up to be a true universal image container.

### Key Features

| Feature | JPEG XL | AVIF | WebP | JPEG |
|---------|---------|------|------|------|
| Lossy compression | Excellent | Excellent | Good | Good |
| Lossless compression | Excellent | Good | Good | No |
| Transparency | Yes | Yes | Yes | No |
| Animation | Yes | Yes | Yes | No |
| HDR support | Native | Yes | No | No |
| Progressive decode | Excellent | Limited | No | Yes |
| JPEG recompression | Lossless | No | No | N/A |
| Max dimensions | 1 billion px | 65535 px | 16383 px | 65535 px |
| Bit depth | Up to 32-bit float | Up to 12-bit | 8-bit | 8-bit |
| Color spaces | ICC v4, wide gamut | ICC, limited | sRGB | sRGB, limited ICC |
| Royalty-free | Yes | Yes (patent pool) | Yes | Yes |

A few of these rows deserve elaboration. The progressive decode capability in jpeg xl is far more refined than JPEG's baseline progressive mode. A JPEG XL file can be meaningfully previewed at as little as 1-2% of total bytes, and quality scales smoothly as more data arrives. AVIF, by contrast, must decode entire tiles before any pixels appear. For large hero images on slow connections, that difference is stark.

The maximum dimension of one billion pixels per side is largely theoretical, but it signals that the jxl format was designed with future display technology in mind — gigapixel panoramas, medical imaging, and satellite photography all benefit from a format that does not impose arbitrary resolution ceilings.

## Real-World Compression Benchmarks

The single-image numbers above show what JPEG XL can do with one file. To compare formats fairly, our [Benchmark Lab](/benchmarks/) encoded 86 images with mozjpeg, libwebp, libaom AVIF and libjxl at 14 quality settings each, scored every result with SSIMULACRA2, and compared the bytes each format needs to reach the same score. The corpus is the Kodak suite, a 50-photo sample of Unsplash Lite and 12 web page screenshots.

Median file size against mozjpeg at score 70 (high quality), measured in October 2026:

| Content (images) | WebP (cwebp -m 6) | AVIF (avifenc -s 6) | JPEG XL (cjxl -e 7) |
|---|---|---|---|
| All photos (74) | 7% smaller | 31% smaller | 23% smaller |
| Unsplash sample (50) | 9% smaller | 40% smaller | 33% smaller |
| Kodak suite (24) | 3% smaller | 21% smaller | 13% smaller |
| Screenshots (12) | 37% smaller | 50% smaller | 30% smaller |

At high quality, AVIF needed fewer bytes than JPEG XL in every group. The order changes near visually lossless quality. At score 90, JPEG XL needed a median 2.22 bits per pixel on photos against 2.74 for AVIF, and it reached that score on all 12 screenshots, where AVIF reached it on 6. Mozjpeg with 4:2:0 chroma reached score 90 on only 26 of the 74 photos.

So the honest summary is: for typical web delivery quality, AVIF compresses photos slightly better; for archival, print and near-lossless delivery, JPEG XL is the stronger choice, and it adds lossless JPEG recompression, which AVIF cannot do. Your own images can differ, so test a sample. The [raw measurements](/benchmarks/latest.csv) and the script are public.

## JPEG XL vs AVIF: Head-to-Head Comparison

The jpeg xl vs avif debate is one of the most common questions in image optimization today. Both formats offer dramatic improvements over legacy JPEG, but they take fundamentally different approaches and have different strengths.

### Architecture Differences

AVIF is built on the AV1 video codec. It inherits AV1's tile-based architecture and block-based transform coding, which means it shares both the strengths and limitations of a system designed primarily for video. Encoding is computationally expensive, and the format imposes a hard resolution limit of 65,535 pixels per dimension (though tiling can work around this for some use cases).

JPEG XL was purpose-built as an image codec. Its VarDCT mode (for lossy) and Modular mode (for lossless) were designed specifically for still images. This means the encoder can make decisions optimized for a single frame rather than adapting video-oriented heuristics.

### Detailed Feature Comparison

| Criterion | JPEG XL | AVIF |
|-----------|---------|------|
| **Lossy efficiency (photos)** | 23% smaller than mozjpeg at high quality; ahead of AVIF near visually lossless | 31% smaller than mozjpeg at high quality |
| **Lossless efficiency** | Best in class | Good, but larger files |
| **Encode speed** | Fast (seconds for 24MP) | Slow (often 10-30s for 24MP) |
| **Decode speed** | Very fast | Moderate |
| **Progressive loading** | Smooth, byte-level | Tile-based, less granular |
| **JPEG recompression** | Lossless, 15% smaller in our test | Not possible |
| **HDR support** | Native PQ/HLG, up to 32-bit | Via AV1 HDR, up to 12-bit |
| **Animation** | Full support | Full support |
| **Max resolution** | 1 billion px | 65,535 px (8K tiling) |
| **Spec maturity** | ISO standard since 2022 | Based on AV1 (mature) |
| **Browser support (2026)** | Safari 17+ and Chrome 155+; check other required clients | All major browsers |
| **Patent situation** | Royalty-free, no pool | AV1 patent pool (royalty-free intent) |

### When to Choose Each Format

**Choose AVIF when:**
- You need broad browser support right now
- Your images are primarily photographs at moderate resolutions
- You can tolerate slower encode times (or use a CDN that encodes for you)
- You need animated images with wide compatibility

**Choose JPEG XL when:**
- You are targeting Safari users (17+) or serving through a format-negotiating CDN
- You need lossless JPEG transcoding for archival
- Encode/decode speed matters (real-time pipelines, edge computing)
- You are working with HDR, wide-gamut, or very high-resolution images
- Progressive loading is important for your user experience
- You are archiving a large JPEG library and want lossless size reduction

In practice, the best strategy today is to generate both formats and let the client or CDN negotiate. Services like [Sirv](https://sirv.com/) handle this negotiation transparently — they detect browser capabilities and serve whichever format yields the smallest file for that client.

## JPEG XL Browser Support in 2026

As of this editorial update, [Chrome ships JPEG XL decoding from version 155](https://developer.chrome.com/blog/jpeg-xl-in-chrome), following its earlier flagged implementation in Chrome 145. [Safari added support in version 17](https://webkit.org/blog/14445/webkit-features-in-safari-17-0/). Check other browser releases and embedded clients separately instead of assuming all applications update together.

### What the shipping milestone means

JPEG XL is now an option for supported web clients as well as compatible archival workflows. Test the encoder output, content type, required features, and fallback behavior on the clients you serve. Browser decoding support does not mean every image editor, upload form, or CDN can generate or accept the same file.

### Keep the fallback path

Use a picture source or server negotiation only after confirming the client’s capability. Retain a suitable JPEG, WebP, or other fallback. For archival JPEG reconstruction, verify a round trip with your actual tools and keep independent backups; a smaller archive should not be your only copy.

### Checking Support in JavaScript

```javascript
async function supportsJxl() {
  const img = new Image();

  return new Promise((resolve) => {
    img.onload = () => resolve(true);
    img.onerror = () => resolve(false);
    img.src = 'data:image/jxl;base64,/woIELASCAgQAFwASxLFgkWAHL0xqnCBCV0qDp901Te/5QM=';
  });
}

// Usage with format negotiation
async function loadOptimalImage(basePath) {
  const jxlSupported = await supportsJxl();

  if (jxlSupported) {
    return `${basePath}.jxl`;
  }

  // Fall back to other checks or default
  return `${basePath}.jpg`;
}
```

## Why JPEG XL Matters

### 1. Lossless JPEG Transcoding

JPEG XL can convert existing JPEGs with **zero quality loss** and ~20% size reduction. This is completely unique to the jxl format and is enormously valuable for anyone managing large photo libraries, archives, or media servers. No other format can reduce the size of an existing JPEG without introducing additional generational loss.

The transcoding is bitwise reversible — you can convert a JPEG to JXL and back to JPEG, and the output file will be byte-for-byte identical to the original. This property makes JPEG XL the only safe format for archiving JPEG originals.

### 2. Superior Progressive Loading

JPEG XL's progressive decoding provides a usable preview at just 1-2% of data loaded, with quality improving smoothly and continuously as more bytes arrive. Unlike JPEG's coarse progressive mode (which loads in distinct visible passes), JXL's approach is nearly seamless — users see the image sharpen gradually rather than watching blocky layers snap into place.

For image-heavy pages on mobile networks, this translates to a dramatically better perceived performance. A 2 MB hero image can show a recognizable preview after just 20-40 KB have been downloaded.

### 3. HDR and Wide Gamut

Native support for HDR10, HLG, and PQ transfer functions alongside Display P3, Rec. 2020, and arbitrary ICC v4 color spaces. With HDR displays becoming standard on phones, laptops, and monitors, jpeg xl is the only web image format with truly first-class HDR support — up to 32-bit floating-point precision per channel.

### 4. Encoding Speed

JPEG XL encodes significantly faster than AVIF at equivalent quality. On a modern desktop CPU, encoding a 24MP photograph takes 2-5 seconds with cjxl versus 15-60 seconds with a comparable AVIF encoder. For build pipelines processing thousands of images, that difference is measured in hours.

## JPEG XL Encoding Tools & Options

### libjxl (Reference Implementation)

The reference encoder and decoder ship as `cjxl` (compress) and `djxl` (decompress). libjxl is actively maintained and available on all major platforms.

**Installation:**

```bash
# Ubuntu/Debian
sudo apt install libjxl-tools

# macOS (Homebrew)
brew install libjxl

# Arch Linux
sudo pacman -S libjxl

# From source (latest)
git clone https://github.com/libjxl/libjxl.git --recursive
cd libjxl
mkdir build && cd build
cmake -DCMAKE_BUILD_TYPE=Release ..
make -j$(nproc)
sudo make install
```

### cjxl Encoding Flags

```bash
# Basic lossy encoding (quality 1-100, 80 is a good default for photos)
cjxl input.png output.jxl -q 80

# Lossless encoding
cjxl input.png output.jxl -q 100

# Lossless JPEG transcoding (bitwise reversible)
cjxl input.jpg output.jxl --lossless_jpeg=1

# Control effort (1=fastest, 10=smallest file, default=7)
cjxl input.png output.jxl -q 80 -e 7

# Enable progressive encoding (great for web delivery)
cjxl input.png output.jxl -q 80 --progressive

# Specify number of threads
cjxl input.png output.jxl -q 80 --num_threads=8

# Target a specific bits-per-pixel instead of quality
cjxl input.png output.jxl -d 1.0
```

The `-e` (effort) flag controls the encode speed vs. file size tradeoff. Effort 1 is extremely fast but produces larger files. Effort 9-10 squeezes out every last byte but can be slow. For most workflows, effort 7 (the default) is the right balance.

### ImageMagick 7.x

ImageMagick 7.1+ includes JXL read/write support via libjxl:

```bash
# Convert PNG to JXL
magick input.png -quality 80 output.jxl

# Convert JXL back to PNG
magick input.jxl output.png

# Batch convert an entire directory
magick mogrify -format jxl -quality 80 *.png

# Resize and convert in one step
magick input.png -resize 1920x1080 -quality 82 output.jxl
```

### Squoosh & GUI Tools

Google's [Squoosh](https://squoosh.app/) web app includes a JPEG XL encoder, making it the easiest way to experiment with the format without installing anything. Drag in an image, select "JXL" as the output format, and adjust the quality slider.

For desktop use, XnView MP and IrfanView (with plugins) both support viewing and converting JXL files.

### Batch Encoding Script

Here is a practical bash script for converting an entire image directory to JXL:

```bash
#!/bin/bash
# batch-encode-jxl.sh — Convert all images in a directory to JPEG XL
# Usage: ./batch-encode-jxl.sh /path/to/images [quality] [effort]

INPUT_DIR="${1:-.}"
QUALITY="${2:-80}"
EFFORT="${3:-7}"
OUTPUT_DIR="${INPUT_DIR}/jxl"

mkdir -p "$OUTPUT_DIR"

echo "Encoding images from $INPUT_DIR to JXL (quality=$QUALITY, effort=$EFFORT)"

find "$INPUT_DIR" -maxdepth 1 \( -iname '*.jpg' -o -iname '*.jpeg' -o -iname '*.png' \) | while read -r file; do
  filename=$(basename "$file")
  base="${filename%.*}"
  ext="${filename##*.}"

  # Use lossless JPEG transcoding for JPEG inputs
  if [[ "${ext,,}" == "jpg" || "${ext,,}" == "jpeg" ]]; then
    echo "  [JPEG lossless] $filename -> ${base}.jxl"
    cjxl "$file" "$OUTPUT_DIR/${base}.jxl" --lossless_jpeg=1 -e "$EFFORT"
  else
    echo "  [lossy q$QUALITY] $filename -> ${base}.jxl"
    cjxl "$file" "$OUTPUT_DIR/${base}.jxl" -q "$QUALITY" -e "$EFFORT" --progressive
  fi
done

echo "Done. Output in $OUTPUT_DIR"
```

## JPEG XL for Archival & Photography

One of the most compelling and practical uses for jpeg xl today — independent of browser support — is archiving existing JPEG libraries. The lossless JPEG transcoding feature is unique to the jxl format and deserves a detailed walkthrough.

### Understanding Lossless JPEG Transcoding

When you encode a JPEG into JPEG XL with `--lossless_jpeg=1`, the encoder does not decode the JPEG to pixels and re-encode. Instead, it restructures the existing DCT coefficients into JXL's more efficient container. This means:

1. **Zero quality loss** — not "visually lossless," literally mathematically identical
2. **~20% average size reduction** — free storage savings
3. **Bitwise reversibility** — you can reconstruct the original JPEG byte-for-byte with `djxl`

### Step-by-Step Archival Workflow

**Step 1: Verify your source files**

```bash
# Count JPEGs and total size
find /photos -iname '*.jpg' -o -iname '*.jpeg' | wc -l
find /photos -iname '*.jpg' -o -iname '*.jpeg' -exec du -cb {} + | tail -1
```

**Step 2: Transcode to JXL (preserving directory structure)**

```bash
#!/bin/bash
# archive-to-jxl.sh — Lossless JPEG-to-JXL archival with verification
SOURCE="/photos"
DEST="/photos-jxl"

find "$SOURCE" -iname '*.jpg' -o -iname '*.jpeg' | while read -r src; do
  # Mirror directory structure
  rel="${src#$SOURCE/}"
  dest_dir="$DEST/$(dirname "$rel")"
  base="$(basename "${rel%.*}")"
  dest_file="$dest_dir/${base}.jxl"

  mkdir -p "$dest_dir"

  if [[ -f "$dest_file" ]]; then
    echo "SKIP (exists): $rel"
    continue
  fi

  echo "ENCODE: $rel"
  cjxl "$src" "$dest_file" --lossless_jpeg=1 -e 7
done
```

**Step 3: Verify roundtrip integrity**

This is the critical step — confirm you can reconstruct the originals before deleting anything:

```bash
#!/bin/bash
# verify-roundtrip.sh — Confirm lossless transcoding is reversible
SOURCE="/photos"
JXL_DIR="/photos-jxl"
TEMP_DIR=$(mktemp -d)
FAILURES=0

find "$JXL_DIR" -iname '*.jxl' | head -100 | while read -r jxl; do
  rel="${jxl#$JXL_DIR/}"
  base="$(basename "${rel%.*}")"
  orig_jpg="$SOURCE/$(dirname "$rel")/${base}.jpg"

  if [[ ! -f "$orig_jpg" ]]; then
    orig_jpg="$SOURCE/$(dirname "$rel")/${base}.jpeg"
  fi

  # Decompress JXL back to JPEG
  djxl "$jxl" "$TEMP_DIR/roundtrip.jpg"

  # Compare checksums
  orig_hash=$(sha256sum "$orig_jpg" | cut -d' ' -f1)
  rt_hash=$(sha256sum "$TEMP_DIR/roundtrip.jpg" | cut -d' ' -f1)

  if [[ "$orig_hash" == "$rt_hash" ]]; then
    echo "OK: $rel"
  else
    echo "FAIL: $rel (hashes differ)"
    FAILURES=$((FAILURES + 1))
  fi
done

rm -rf "$TEMP_DIR"
echo "Verification complete. Failures: $FAILURES"
```

**Step 4: Measure savings**

```bash
# Compare total sizes
echo "Original JPEGs:"
du -sh /photos
echo "JXL archive:"
du -sh /photos-jxl
```

For a typical photo library, expect 18-22% size reduction. On a 1 TB photo archive, that saves roughly 200 GB — with zero quality loss and full reversibility.

### Why Photographers Should Care

For professional photographers and archivists, jpeg xl solves a real problem. RAW files are the gold standard for archival, but they are enormous. JPEGs are small but lossy. JPEG XL's lossless transcoding gives you a smaller-than-JPEG archival format that preserves every bit of the original. If you ever need the JPEG back (for legacy software, client delivery, or print workflows), a single `djxl` command reconstructs it perfectly.

## Implementation Strategies

### Progressive Enhancement with `<picture>`

The `<picture>` element lets you offer multiple formats and the browser selects the first one it supports:

```html
<picture>
  <source srcset="image.jxl" type="image/jxl">
  <source srcset="image.avif" type="image/avif">
  <source srcset="image.webp" type="image/webp">
  <img src="image.jpg" alt="Description" loading="lazy">
</picture>
```

List formats from newest to oldest. Browsers that support JXL (Safari 17+) will select the first source. Others fall through to AVIF, WebP, or finally JPEG.

For responsive images, combine format sources with `sizes` and `srcset`:

```html
<picture>
  <source
    srcset="image-400.jxl 400w, image-800.jxl 800w, image-1200.jxl 1200w"
    sizes="(max-width: 600px) 400px, (max-width: 1000px) 800px, 1200px"
    type="image/jxl"
  >
  <source
    srcset="image-400.avif 400w, image-800.avif 800w, image-1200.avif 1200w"
    sizes="(max-width: 600px) 400px, (max-width: 1000px) 800px, 1200px"
    type="image/avif"
  >
  <img
    src="image-800.jpg"
    srcset="image-400.jpg 400w, image-800.jpg 800w, image-1200.jpg 1200w"
    sizes="(max-width: 600px) 400px, (max-width: 1000px) 800px, 1200px"
    alt="Description"
    loading="lazy"
    decoding="async"
  >
</picture>
```

### Using Image CDNs

CDNs like [Sirv](https://sirv.com/) handle format negotiation automatically:

```html
<img src="https://your-site.sirv.com/photos/sunset.jpg?format=optimal">
```

When browsers support JPEG XL, CDNs can serve it automatically without code changes. This is the lowest-friction path to adopting new formats — upload once, and the CDN converts and caches each format as needed. [Sirv](https://sirv.com/) supports JPEG XL alongside AVIF, WebP, and legacy formats, detecting the optimal choice per request via the `Accept` header.

## JPEG XL in Build Pipelines

Generating JXL files at build time ensures they are ready to serve without runtime encoding overhead. Here are practical configurations for popular frameworks.

### Vite (with vite-plugin-image-optimizer)

```javascript
// vite.config.js
import { defineConfig } from 'vite';
import { ViteImageOptimizer } from 'vite-plugin-image-optimizer';

export default defineConfig({
  plugins: [
    ViteImageOptimizer({
      jxl: {
        quality: 80,
        effort: 7,
        progressive: true,
      },
      avif: {
        quality: 65,
      },
      webp: {
        quality: 80,
      },
    }),
  ],
});
```

### Webpack (with image-minimizer-webpack-plugin)

```javascript
// webpack.config.js
const ImageMinimizerPlugin = require('image-minimizer-webpack-plugin');

module.exports = {
  optimization: {
    minimizer: [
      new ImageMinimizerPlugin({
        generator: [
          {
            preset: 'jxl',
            implementation: ImageMinimizerPlugin.sharpGenerate,
            options: {
              encodeOptions: {
                jxl: {
                  quality: 80,
                  effort: 7,
                },
              },
            },
          },
          {
            preset: 'avif',
            implementation: ImageMinimizerPlugin.sharpGenerate,
            options: {
              encodeOptions: {
                avif: { quality: 65 },
              },
            },
          },
        ],
      }),
    ],
  },
};
```

### Astro (with astro-imagetools)

```javascript
// astro.config.mjs
import { defineConfig } from 'astro/config';

export default defineConfig({
  image: {
    service: {
      entrypoint: 'astro/assets/services/sharp',
      config: {
        // Sharp 0.33+ supports JXL output
        jxl: {
          quality: 80,
          effort: 7,
        },
      },
    },
  },
});
```

In your Astro components, use the `<Picture>` component for multi-format output:

```astro
---
import { Picture } from 'astro:assets';
import heroImage from '../assets/hero.jpg';
---

<Picture
  src={heroImage}
  formats={['jxl', 'avif', 'webp']}
  alt="Hero image"
  widths={[400, 800, 1200]}
/>
```

### Next.js (Custom Image Loader with Sharp)

Next.js does not natively output JXL from its image optimization pipeline yet, but you can generate JXL files at build time with a custom script:

```javascript
// scripts/generate-jxl.mjs
import sharp from 'sharp';
import { glob } from 'glob';
import path from 'path';
import fs from 'fs';

const images = await glob('public/images/**/*.{jpg,jpeg,png}');

for (const imagePath of images) {
  const outputPath = imagePath.replace(/\.(jpg|jpeg|png)$/i, '.jxl');

  if (fs.existsSync(outputPath)) continue;

  await sharp(imagePath)
    .jxl({ quality: 80, effort: 7 })
    .toFile(outputPath);

  const original = fs.statSync(imagePath).size;
  const compressed = fs.statSync(outputPath).size;
  const savings = ((1 - compressed / original) * 100).toFixed(1);

  console.log(`${path.basename(imagePath)} -> JXL (${savings}% smaller)`);
}
```

Add it to your build script in `package.json`:

```json
{
  "scripts": {
    "prebuild": "node scripts/generate-jxl.mjs",
    "build": "next build"
  }
}
```

## Server-Side JXL Detection

To serve JXL files efficiently, your server needs to detect client support via the `Accept` request header. Browsers that support jpeg xl include `image/jxl` in their `Accept` header.

### Nginx Configuration

```nginx
# /etc/nginx/conf.d/jxl.conf

map $http_accept $jxl_suffix {
    default   "";
    "~image/jxl"  ".jxl";
}

map $http_accept $avif_suffix {
    default   "";
    "~image/avif"  ".avif";
}

map $http_accept $webp_suffix {
    default   "";
    "~image/webp"  ".webp";
}

server {
    listen 443 ssl;
    server_name example.com;

    location ~* ^(/images/.+)\.(jpg|jpeg|png)$ {
        set $base $1;
        set $ext  $2;

        # Try JXL first, then AVIF, then WebP, then original
        add_header Vary Accept;
        try_files $base$jxl_suffix $base$avif_suffix $base$webp_suffix $uri =404;
    }
}
```

This configuration checks the `Accept` header, and if the browser signals JXL support, Nginx serves the `.jxl` file from the same directory. The `Vary: Accept` header is critical — it tells caches that the response depends on the `Accept` header, preventing a cached JXL from being served to a browser that cannot decode it.

### Apache (.htaccess)

```apache
<IfModule mod_rewrite.c>
  RewriteEngine On

  # Serve JXL if supported and file exists
  RewriteCond %{HTTP_ACCEPT} image/jxl
  RewriteCond %{REQUEST_URI} (.+)\.(jpg|jpeg|png)$
  RewriteCond %{DOCUMENT_ROOT}%1.jxl -f
  RewriteRule (.+)\.(jpg|jpeg|png)$ $1.jxl [T=image/jxl,E=ORIGINAL_EXT:%2,L]

  # Serve AVIF if supported and file exists
  RewriteCond %{HTTP_ACCEPT} image/avif
  RewriteCond %{REQUEST_URI} (.+)\.(jpg|jpeg|png)$
  RewriteCond %{DOCUMENT_ROOT}%1.avif -f
  RewriteRule (.+)\.(jpg|jpeg|png)$ $1.avif [T=image/avif,E=ORIGINAL_EXT:%2,L]

  # Serve WebP if supported and file exists
  RewriteCond %{HTTP_ACCEPT} image/webp
  RewriteCond %{REQUEST_URI} (.+)\.(jpg|jpeg|png)$
  RewriteCond %{DOCUMENT_ROOT}%1.webp -f
  RewriteRule (.+)\.(jpg|jpeg|png)$ $1.webp [T=image/webp,E=ORIGINAL_EXT:%2,L]
</IfModule>

<IfModule mod_headers.c>
  # Add Vary header for proper caching
  Header append Vary Accept env=ORIGINAL_EXT
</IfModule>

# Register MIME type
AddType image/jxl .jxl
```

### CDN Configuration (Cloudflare / Generic)

Most CDNs can be configured to respect the `Accept` header for format selection. If your CDN supports edge workers or transform rules:

```javascript
// Cloudflare Worker — format negotiation
addEventListener('fetch', (event) => {
  event.respondWith(handleRequest(event.request));
});

async function handleRequest(request) {
  const url = new URL(request.url);
  const accept = request.headers.get('Accept') || '';

  // Only process image requests
  if (!/\.(jpg|jpeg|png)$/i.test(url.pathname)) {
    return fetch(request);
  }

  const basePath = url.pathname.replace(/\.(jpg|jpeg|png)$/i, '');

  // Try formats in order of preference
  if (accept.includes('image/jxl')) {
    const jxlResponse = await fetch(new URL(basePath + '.jxl', url.origin));
    if (jxlResponse.ok) {
      const response = new Response(jxlResponse.body, jxlResponse);
      response.headers.set('Content-Type', 'image/jxl');
      response.headers.set('Vary', 'Accept');
      return response;
    }
  }

  if (accept.includes('image/avif')) {
    const avifResponse = await fetch(new URL(basePath + '.avif', url.origin));
    if (avifResponse.ok) {
      const response = new Response(avifResponse.body, avifResponse);
      response.headers.set('Content-Type', 'image/avif');
      response.headers.set('Vary', 'Accept');
      return response;
    }
  }

  // Fall through to original
  return fetch(request);
}
```

Alternatively, using a CDN like [Sirv](https://sirv.com/) eliminates the need for any server-side configuration. Sirv handles Accept header parsing, format encoding, caching, and delivery automatically.

## Creating JPEG XL Images

### Quality Guidelines

| Content Type | Quality | Effort | Notes |
|-------------|---------|--------|-------|
| Photographs | 75-85 | 7 | Good balance of size and fidelity |
| E-commerce products | 80-88 | 7-8 | Preserve product details |
| Graphics/illustrations | 85-95 | 7 | Preserve sharp edges |
| Screenshots | 90-100 | 7 | Near-lossless for text clarity |
| Archival (from JPEG) | lossless_jpeg | 7 | Bitwise-reversible transcoding |
| Archival (from PNG/RAW) | 100 | 9 | Mathematically lossless, maximum compression |
| Thumbnails | 65-75 | 5 | Faster encoding, still good quality |

## Migration Strategy

### Phase 1: Preparation (Now)

Generate JXL alongside other formats in your build pipeline. This costs only disk space and build time — there is no risk, since no browser will receive a file it cannot decode if you use `<picture>` or server-side negotiation.

Start by adding JXL generation to your asset pipeline (see the build pipeline section above). Store generated JXL files alongside your existing AVIF and WebP variants.

### Phase 2: Conditional Serving (Now)

Use `<picture>` with JXL as the first source. Safari 17+ users (a significant share of iOS traffic) will receive JXL files today, benefiting from smaller payloads and faster progressive loading.

If you use a CDN like [Sirv](https://sirv.com/), this phase requires zero code changes — the CDN automatically serves JXL to clients that support it.

### Phase 3: Primary Format (Future)

When Chrome enables its flag by default (or Firefox enables its own), jpeg xl could become the primary format for the web. At that point, you could simplify your pipeline to generate only JXL and JPEG (as a legacy fallback), rather than maintaining four separate format variants.

## The Future of JPEG XL

Despite the browser support challenges, the jpeg xl ecosystem continues to grow across multiple fronts.

### Industry Adoption

**Apple** has been the strongest corporate backer. Beyond Safari, JPEG XL is supported natively in macOS, iOS, and visionOS at the system level. Apple's Photos app, Preview, and Core Image framework all support the jxl format. This deep OS integration means third-party apps on Apple platforms get JXL support for free.

**Adobe** added JPEG XL support to Camera Raw and Lightroom. For the photography community, Adobe's endorsement carries significant weight and validates JXL as a serious archival and editing format.

**The Krita project** and other open-source creative tools have added JXL support, giving artists and designers access to the format's superior lossless compression for their working files.

**Samsung** has shown interest in JXL for its camera pipeline, and several Android camera apps now support JXL output.

### Standardization Status

JPEG XL is formally standardized as ISO/IEC 18181 (Parts 1-4). This is a full international standard, not a draft or proposal. The specification covers the codestream format, file container, conformance testing, and reference software. This level of standardization provides long-term stability — the format will not change in backward-incompatible ways.

### What Needs to Happen

Chrome’s shipping milestone has changed the adoption question. Evaluate current audience coverage, output quality, processing cost, and fallback behavior using [the primary release evidence](https://developer.chrome.com/blog/jpeg-xl-in-chrome) rather than waiting on the earlier flag-only status.

The most likely paths forward:

1. **Chrome enables `enable-jxl-image-format` by default.** The decoder already ships in the binary, so this is a configuration decision rather than an engineering one. No date has been announced.
2. **Mozilla enables `image.jxl.enabled` by default in Firefox.** Both vendors appear to be waiting for production evidence, and for each other.
3. **Apple mandates or strongly encourages JXL in App Store imagery.** This would accelerate tooling and ecosystem development.

### What You Should Do Today

Regardless of Chrome's timeline, adopting jpeg xl today is a low-risk, high-reward strategy:

1. **Generate JXL files** in your build pipeline alongside AVIF and WebP
2. **Serve conditionally** using `<picture>` elements or server-side content negotiation
3. **Use JXL for archival** — the lossless JPEG transcoding feature works now and saves real storage costs
4. **Choose a CDN** like [Sirv](https://sirv.com/) that handles format negotiation automatically, so you benefit from JXL support the moment any browser adds it
5. **Monitor browser support** — the landscape could change rapidly once one more major browser commits

## Conclusion

JPEG XL is the most complete still-image format available today. In our benchmark it needed a median 23% fewer bytes than mozjpeg on photos at high quality and beat AVIF near visually lossless quality. It also offers lossless JPEG recompression that no other format can match, and native HDR support.

Browser support now includes Safari 17 and Chrome 155, but client requirements and downstream tooling still matter. Compare actual output, processing cost, and fallback behavior instead of treating either JPEG XL or AVIF as a universal winner.

For now, the winning strategy is straightforward:

1. Generate JXL alongside other formats in your build pipeline
2. Serve conditionally using `<picture>` or server-side `Accept` header negotiation
3. Use JXL for archival and photography workflows where it provides immediate, tangible benefits
4. Monitor browser support for changes — the situation is evolving
5. Use CDNs like [Sirv](https://my.sirv.com/#/signup) that can add JXL support automatically, so your infrastructure is ready the moment the format goes mainstream

## Sources

- [JPEG XL, JPEG committee](https://jpeg.org/jpegxl/)
- [libjxl reference implementation](https://github.com/libjxl/libjxl)
