Skip to main content
Version: 3.x

createResizedImageResponse

The createResizedImageResponse allows to create resource routes which allow resizing and caching images on the fly.

Usage

The createResizedImageResponse function has 3 parameters:

  • request:The request to handle.
  • fetchRemoteImage: A function that returns the image buffer.
  • cacheConfig: The optional cache configuration which handles the caching of an image

This can be used to serve images either from a remote service, or from a local file system, next we will see examples for both cases.

Remote image

For this example, we will create a splat route that will fetch an image from a remote service.

To do so, we will introduce the createResizedImageResponse function.

/app/routes/media.picsum.$.ts
import type { LoaderFunctionArgs } from "@remix-run/node";
import { createResizedImageResponse } from "@front-commerce/core/resizedImage.server";

const fetchRemoteImage = async (imagePath: string) => {
const image = await fetch(`https://picsum.photos/${imagePath}`);
return image.arrayBuffer();
};

export const loader = async ({ request, params }: LoaderFunctionArgs) => {
const imagePath = params["*"] as string;

const ONE_WEEK = 7 * 24 * 60 * 60; // the default cache duration is set to one year

return createResizedImageResponse(
request,
() => fetchRemoteImage(imagePath),
{
cacheDuration: ONE_WEEK,
}
);
};
info

When we visit the /media/picsum/200/300.jpg?format=large&extension=webp route, the image will be retrieved from the https://picsum.photos/200/300 URL and resized to the same size defined in your images config for the large format, and it will be converted to a webp image.

Local image

For this example, we will create a new route that will fetch an image from a local directory

/app/routes/media.local.$.ts
import type { LoaderFunctionArgs } from "@remix-run/node";
import { createResizedImageResponse } from "@front-commerce/core/resizedImage.server";
import fs from "fs";

const fetchLocalImage = (relativePath: string) => {
try {
return fs.readFileSync(relativePath);
} catch (error) {
console.error(error);
throw new Response("Image not found", { status: 404 });
}
};

export const loader = async ({ request, params }: LoaderFunctionArgs) => {
const imagePath = params["*"] as string;

const relativePath = path.resolve(
process.cwd(),
`public/images/${imagePath}`
);

return createResizedImageResponse(request, () =>
fetchLocalImage(relativePath)
);
};
info

When we visit the /media/local/my-image.jpg?format=large&extension=webp route, the image will be retrieved from the public/images/my-image.jpg file and resized to the same size defined in your images config for the large format, and it will be converted to a webp image.