shadimage
utilcn
libgenerate-presigned-download-urlsource: ok · hit

Generate Presigned Download URL

Generate a presigned download URL for a file.

npx shadcn add "https://utilcn.dev/r/generate-presigned-download-url.json"
free

No selection tags yet — empty means no evidence, not lack of support.

Dependencies

Bundle weight · light
@aws-sdk/client-s3@aws-sdk/s3-request-presigner

Files2 · source cached 10/14/2026, 11:42:33 AM

registry/default/storage/generate-presigned-download-url.ts
import { GetObjectCommand } from '@aws-sdk/client-s3';
import { getSignedUrl } from '@aws-sdk/s3-request-presigner';

import { getS3Client } from '@/registry/default/storage/s3-client';

export async function generatePresignedDownloadUrl(
  key: string,
  expiresIn = 3600,
) {
  try {
    const command = new GetObjectCommand({
      Bucket: process.env.S3_BUCKET_NAME,
      Key: key,
    });

    const url = await getSignedUrl(getS3Client(), command, { expiresIn });
    return url;
  } catch (err) {
    console.error({ err }, 'Failed to generate download URL');
    throw new Error('Failed to generate download URL');
  }
}
registry/default/storage/s3-client.ts
import { S3Client } from '@aws-sdk/client-s3';

let s3Client: S3Client | null = null;

export const getS3Client = (): S3Client => {
  if (s3Client) {
    return s3Client;
  }

  if (
    !process.env.S3_REGION ||
    !process.env.S3_ENDPOINT ||
    !process.env.S3_ACCESS_KEY ||
    !process.env.S3_SECRET_KEY
  ) {
    throw new Error('Missing S3 environment variables');
  }

  s3Client = new S3Client({
    region: process.env.S3_REGION,
    endpoint: process.env.S3_ENDPOINT,
    forcePathStyle: true, // Required for some S3-compatible services
    credentials: {
      accessKeyId: process.env.S3_ACCESS_KEY,
      secretAccessKey: process.env.S3_SECRET_KEY,
    },
  });

  return s3Client;
};

More from utilcn

Browse all components in this library →