Back to all posts

Serve an image from a resource route

This article was written for Remix 2, which has been merged into React Router 7. Some changes may be necessary.

Remix uses esbuild to bundle your app. When you import a file, esbuild will use its file-loader to copy the file to the public build directory and return the path to the file. This is useful for images, fonts, and other static assets.

A resource route can fetch the image from this path and return it as a response to serve it to the client.

import { LoaderFunctionArgs } from "@remix-run/node"
import image from "./image.jpg"
 
export async function loader({ request }: LoaderFunctionArgs) {
  const url = new URL(request.url)
  url.pathname = image
 
  const imageBuffer = await fetch(url).then(
    (res) => res.body,
  )
 
  return new Response(imageBuffer, {
    headers: {
      "Content-Type": "image/jpeg",
    },
  })
}