Back to roadmaps supabase Course

File Uploads and Public URL Generation

Let us look at using the Supabase JavaScript SDK to upload files from the browser and generate shareable URL paths.


1. Uploading Files from a File Input

To upload files, select the target bucket using .from() and call the .upload() method:

import { supabase } from "../lib/supabase";

async function uploadAvatar(userId: string, file: File) {
  // Save files in user-specific folder paths to avoid file conflicts
  const filePath = `${userId}/${file.name}`;

  const { data, error } = await supabase.storage
    .from("avatars")
    .upload(filePath, file, {
      cacheControl: "3600",
      upsert: true, // Overwrite file if it already exists
    });

  if (error) {
    console.error("Upload failed:", error.message);
    return null;
  }

  console.log("Upload successful:", data.path);
  return data.path;
}

2. Generating Public Links (For Public Buckets)

For assets stored inside a public bucket, retrieve the permanent URL path using .getPublicUrl():

function getAvatarPublicLink(filePath: string) {
  const { data } = supabase.storage
    .from("avatars")
    .getPublicUrl(filePath);

  // Returns the complete HTTP asset URL
  console.log("Public URL:", data.publicUrl);
  return data.publicUrl;
}

3. Generating Temporary Signed Links (For Private Buckets)

For assets stored inside private buckets, create a temporary download link using .createSignedUrl():

async function getPrivateDownloadLink(filePath: string) {
  const { data, error } = await supabase.storage
    .from("invoices")
    // Generate a temporary link valid for 60 seconds (1 minute)
    .createSignedUrl(filePath, 60);

  if (error) {
    console.error("Failed to generate download link:", error.message);
    return null;
  }

  // Returns a URL containing a temporary authorization token parameters
  console.log("Temporary URL:", data.signedUrl);
  return data.signedUrl;
}
Published on Last updated: