Install package: ``` npm i wasm-image-optimization ``` Create API route for eg, `api/image/index.ts`: ``` import { optimizeImage } from "wasm-image-optimization/edge"; import type { NextRequest } from "next/server"; /** * A helper function to convert string to number * * @param input A string containing number or null * * @returns Number if input is a string and a valid number otherwise null */ const getNumber = (input: string | null) => { if (input) { const num = Number(input); if (!Number.isNaN(num)) { return num; } } return null; }; /** * A helper function to create URL instance from string * * @param input The url * @param base The base url * * @returns URL if if input is string and not empty otherwise null */ const getURL = (input: string | null, base: string) => { if (input) { const trimmed = input.trim(); if (trimmed) { return new URL(trimmed, base); } } return null; }; export async function GET(request: NextRequest): Promise { const { nextUrl } = request; const { searchParams: params } = nextUrl; const imageUrl = getURL(params.get("url"), nextUrl.origin); if (!imageUrl) { return new Response("404: Specify a valid url parameter", { status: 404 }); } const width = getNumber(params.get("w")); const height = getNumber(params.get("h")); const quality = getNumber(params.get("q")); const imageBuffer = await fetch(imageUrl) .then((res) => (res.ok ? res.arrayBuffer() : null)) .catch(() => null); if (!imageBuffer) { return new Response(`404: Unable to find any image at ${imageUrl.href}`, { status: 404 }); } const image = await optimizeImage({ image: imageBuffer, width: width !== null ? width : undefined, height: height !== null ? height : undefined, quality: quality !== null ? quality : undefined }); const response = new Response(image, { headers: { "Content-Type": "image/webp" } }); return response; } export const runtime = "edge"; ``` Add `images.path` in `next.config.mjs`: ``` //... images: { path: "/api/image/" } //... ```