Fresh+SupabaseでCDNで画像を表示する

作成日
更新日

/api/images/[fileName].tsx

/api/images/[fileName].tsx
import { Handlers } from "$fresh/server.ts";
import { slugifyFileName } from "../../../utils/slugifyFileName.ts";
import { supabase } from "../../../utils/supabase.ts";

export const handler: Handlers = {
  async GET(_req, ctx) {
    const { fileName } = ctx.params;
    const encodeFileName = decodeURIComponent(fileName);
    const safeFileName = slugifyFileName(encodeFileName);
    const bucketName = Deno.env.get("SUPABASE_IMAGE_BUCKET") ?? "";

    const { data, error } = await supabase.storage
      .from(bucketName)
      .createSignedUrl(safeFileName, 60 * 60); // 有効期限 1時間

    if (error || !data?.signedUrl) {
      console.error(`Error creating signed URL for ${safeFileName}:`, error);
      return new Response("Failed to fetch signed URL", { status: 500 });
    }

    // Supabase CDN に直接リダイレクト(302)
    return Response.redirect(data.signedUrl, 302);
  },
};

<img>タグはこれまで通り使える。

<img src="/api/images/cat.jpg" alt="ねこ" />

リンクをタップした時はSupabaseのリンクsignedUrlへアクセスされる。

サイトアイコン
公開日
更新日