utilcn logoutilcn
Storage

generatePresignedDownloadUrl

Generate a presigned URL for secure file downloads from S3-compatible storage

Backend Implementation Required

This function must be implemented on your backend server and cannot be safely exposed to the frontend. The function handles sensitive S3 credentials and should only be called from your server-side code.

CORS Configuration Required

You must configure CORS settings on your S3 bucket or storage provider to allow your frontend domain to download files using the generated presigned URLs. Without proper CORS configuration, downloads will fail with cross-origin errors.

Usage

import { generatePresignedDownloadUrl } from '@/lib/generate-presigned-download-url';

const downloadUrl = await generatePresignedDownloadUrl(
  'file-key',
  3600 // expires in 1 hour
);

Installation

pnpm dlx shadcn@latest add https://utilcn.dev/r/generate-presigned-download-url.json
bunx --bun shadcn@latest add https://utilcn.dev/r/generate-presigned-download-url.json
npx shadcn@latest add https://utilcn.dev/r/generate-presigned-download-url.json
yarn shadcn@latest add https://utilcn.dev/r/generate-presigned-download-url.json

Parameters

ParameterTypeDescriptionDefault
keystringThe S3 object key of the file-
expiresInnumberURL expiration time in seconds3600

Returns

A string containing the presigned download URL that allows temporary access to the file.

Environment Variables

This function requires the following environment variables:

S3_REGION=your-region
S3_ENDPOINT=your-s3-endpoint
S3_ACCESS_KEY=your-access-key
S3_SECRET_KEY=your-secret-key
S3_BUCKET_NAME=your-bucket-name

Dependencies

  • @aws-sdk/client-s3
  • @aws-sdk/s3-request-presigner

Implementation

import { GetObjectCommand } from '@aws-sdk/client-s3';
import { getSignedUrl } from '@aws-sdk/s3-request-presigner';

import { getS3Client } from '@/lib/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');
  }
}

Frontend Integration

downloadFile

Generate presigned URLs for secure file uploads to cloud storage