Frontend Performance35-60 min
Image Optimization with WebP and AVIF
Serve correctly sized images, use modern formats, prioritize above-the-fold media, and lazy-load only offscreen assets.
HTMLNext/ImageSharpCDN
Prerequisites
- A page with large hero, product, or gallery images.
- Access to original image assets.
- A way to generate WebP or AVIF variants.
1
Plan the implementation
Start by choosing the exact page, route, API, or deployment surface you want to improve. A narrow target makes the implementation measurable and easier to verify.
- Write down the current behavior and the user-facing problem it creates.
- Pick one measurable success signal such as bundle size, latency, error rate, security coverage, or UI responsiveness.
- Identify the files, routes, providers, and environment variables involved.
- Create a rollback note before changing production-sensitive configuration.
2
Set up the required tools
Install or configure only the tools needed for this implementation. Keep config close to the feature so future developers can find the moving parts quickly.
Implementation snippet
npm install sharp
# Optional: inspect image weight in DevTools Network.Checklist
- Dependencies are added to the correct workspace package.
- Environment variables are documented in `.env.example` when needed.
- Local development still starts without production-only secrets.
- The change is small enough to review in one pull request.
3
Implement the core pattern
- Find the largest transferred images in the Network tab.
- Resize images to match the largest rendered size needed by the layout.
- Generate WebP or AVIF versions while keeping the original as fallback.
- Set explicit width and height to prevent layout shift.
- Use eager loading or high priority only for the main above-the-fold image.
Implementation snippet
<picture>
<source srcSet="/product.avif" type="image/avif" />
<source srcSet="/product.webp" type="image/webp" />
<img src="/product.jpg" width="1200" height="800" alt="Product screenshot" loading="lazy" decoding="async" />
</picture>4
Handle edge cases
Checklist
- Offscreen images use lazy loading.
- The LCP image is not lazy-loaded.
- Every meaningful image has useful alt text.
- Image bytes are lower without obvious quality loss.
5
Verify before production
- Run the app locally and test the normal success path.
- Test one failure path, one empty state, and one slow-network or retry path.
- Run the project build and any related unit or integration tests.
- Check browser console, server logs, and network responses for hidden warnings.
- Document the final behavior, commands used, and any follow-up work.