Usage & Integration

Practical examples of uploading files to an AWS S3 bucket and using their generated URLs, adaptable to your project’s needs. It includes code snippets for integrating with your app and storing metadata with Prisma.

Plainform uses the AWS S3 client in @/lib/amazon/s3.ts to upload files and generate URLs, validated by t3-env for reliability.

Below are examples of how to implement file uploads and use their URLs in your Next.js application, suitable for use cases like user avatars or document storage, with options to store metadata in your Supabase database via Prisma. Example Use Cases

Use Cases

1. Retrieve Files from S3

  • Retrieve files (e.g., placeholder user avatars) to your API route:
@/api/stripe/orders/route.ts
import { ListObjectsV2Command } from '@aws-sdk/client-s3';
import { s3 } from '@/lib/amazon/s3';

const listObjects = await s3.send(
  new ListObjectsV2Command({
    Bucket: process.env.AWS_S3_BUCKET!,
    Prefix: 'mockupUsers/',
    MaxKeys: 5,
  })
);

2. Upload Files to S3

  • Upload a file to your S3 bucket and retrieve its URL:
@/lib/amazon/uploadFile.ts
import { s3Client } from '@/lib/amazon';
import { PutObjectCommand } from '@aws-sdk/client-s3';

export async function uploadFile(file: File, userId: string) {
  const key = `images/${userId}/${file.name}`;
  const command = new PutObjectCommand({
    Bucket: process.env.AWS_S3_BUCKET!,
    Key: key,
    Body: file,
    ContentType: file.type,
  });

  await s3Client.send(command);
  const url = `https://${process.env.AWS_S3_BUCKET}.s3.${process.env.AWS_REGION}.amazonaws.com/${key}`;
  return url;
}
  • Use this in an API route (e.g., app/api/upload/route.ts) or server action to handle file uploads from a form.

3. Using File URLs in Your App

  • Display the uploaded file in your UI using the generated S3 URL:
@/components/UserProfile.tsx
import Image from "next/image";

interface {
    src: string
    alt: string;
}

export default function AssetFrame({ src, alt }: IAssetFrameProps) {
  return <Image src={src} alt={alt} width={100} height={100} />;
}
  • Use this in an API route (e.g., app/api/upload/route.ts) or server action to handle file uploads from a form.

Important Notes

  • Environment Variables: Ensure AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_REGION, and AWS_S3_BUCKET are set in .env, or t3-env will block app startup.
  • Security: Keep AWS credentials out of client-side code and version control using .gitignore for .env files.
  • Scalability: Configure S3 bucket policies for scalability, such as lifecycle rules to archive old files or versioning for backups.

For advanced S3 features like lifecycle policies or multi-part uploads, consult the AWS S3 Documentation.

How is this guide ?

Last updated on