Skip to content

Instantly share code, notes, and snippets.

@shinmai
Created February 21, 2025 09:42
Show Gist options
  • Save shinmai/ded5a0e474c21884141f456f76567606 to your computer and use it in GitHub Desktop.
Save shinmai/ded5a0e474c21884141f456f76567606 to your computer and use it in GitHub Desktop.
Reddit/Imgur style image serving beautifier as Netlify Edge Function
// netlify/edge-functions/image-handler.js
import mime from "https://esm.sh/mime/lite"
/**
* Checks if client's request headers have an Accept header with text/html,
* and if the client _is_ asking for a web page, serves one, otherwise serves the image file.
*/
export default async (request, context) => {
const url = new URL(request.url)
if (request.headers.get("accept")?.includes("text/html")) {
return new Response(
`<!DOCTYPE html><html lang="en"><head><style>body{margin:0;display:grid;place-items:center;height:100vh}img{max-width:100vw;max-height:100vh}</style><meta charset="UTF-8"><title>${url.pathname.split("/").at(-1)}</title></head><body><img src="${url.pathname}" alt="Image"></body></html>`,
{ headers: { "Content-Type": "text/html" } }
)
} else {
const imageResponse = await context.next()
if (imageResponse.ok) {
const imageBuffer = await imageResponse.arrayBuffer()
return new Response(imageBuffer, { headers: { "Content-Type": mime.getType(url.pathname)||"application/octet-stream" } })
} else {
return new Response(`Image not found: ${url.pathname}.`, { status: 404 })
}
}
}
[[edge_functions]]
function = "image-handler"
path = "/images/*"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment