🎥 Make videos programmatically with React
Update presign article
Jonny Burger516cd5681484
diff --git a/packages/docs/docs/presigned-urls.mdx b/packages/docs/docs/presigned-urls.mdxindex 3555c852d4..dc04884987 100644--- a/packages/docs/docs/presigned-urls.mdx+++ b/packages/docs/docs/presigned-urls.mdx@@ -2,7 +2,7 @@image: /generated/articles-docs-presigned-urls.pngid: presigned-urlstitle: Upload with a presigned URL-crumb: "Building video apps"+crumb: 'Building video apps'---This article provides guidance for webapps wanting to allow users to upload videos and other assets. We recommend to generate a presigned URL server-side that allows a user to directly upload a file into your cloud storage without having to pass the file through your server.@@ -26,10 +26,10 @@ First, accept a file in your frontend, for example using `<input type="file">`.```ts twoslash title="App.tsx"// @module: ESNext// @target: ESNext-import { interpolate } from "remotion";+import {interpolate} from 'remotion';const file: File = {} as unknown as File;// ---cut----const contentType = file.type || "application/octet-stream";+const contentType = file.type || 'application/octet-stream';const arrayBuffer = await file.arrayBuffer();const contentLength = arrayBuffer.byteLength;```@@ -39,10 +39,9 @@ This example uses [`@aws-sdk/s3-request-presigner`](https://github.com/aws/aws-s- `presignedUrl` is a URL to which the file can be uploaded to- `readUrl` is the URL from which the file can be read from.-```tsx twoslash title="api/generate-presigned-url.ts"-import { getSignedUrl } from "@aws-sdk/s3-request-presigner";-import { AwsRegion, getAwsClient } from "@remotion/lambda/client";-import { v4 } from "uuid";+```tsx twoslash title="generate-presigned-url.ts"+import {getSignedUrl} from '@aws-sdk/s3-request-presigner';+import {AwsRegion, getAwsClient} from '@remotion/lambda/client';export const generatePresignedUrl = async (contentType: string,@@ -50,24 +49,24 @@ export const generatePresignedUrl = async (expiresIn: number,bucketName: string,region: AwsRegion,-): Promise<{ presignedUrl: string; readUrl: string }> => {+): Promise<{presignedUrl: string; readUrl: string}> => {if (contentLength > 1024 * 1024 * 200) {throw new Error(`File may not be over 200MB. Yours is ${contentLength} bytes.`,);}- const { client, sdk } = getAwsClient({+ const {client, sdk} = getAwsClient({region: process.env.REMOTION_AWS_REGION as AwsRegion,- service: "s3",+ service: 's3',});- const key = v4();+ const key = crypto.randomUUID();const command = new sdk.PutObjectCommand({Bucket: bucketName,Key: key,- ACL: "public-read",+ ACL: 'public-read',ContentLength: contentLength,ContentType: contentType,});@@ -76,10 +75,10 @@ export const generatePresignedUrl = async (expiresIn,});- // The location of the assset after the upload+ // The location of the asset after the uploadconst readUrl = `https://${bucketName}.s3.${region}.amazonaws.com/${key}`;- return { presignedUrl, readUrl };+ return {presignedUrl, readUrl};};```@@ -90,30 +89,196 @@ Explanation:- A [UUID](https://en.wikipedia.org/wiki/Universally_unique_identifier) gets used as the filename to avoid name clashes.- Finally, the presigned URL and output URL get calculated and returned.-## Using the presigned URL+### Next.js example code++Here is a sample snippet for the Next.js App Router.+The endpoint is available under `api/upload/route.ts`.++```tsx twoslash title="app/api/upload/route.ts"+import {NextResponse} from 'next/server';+import {getSignedUrl} from '@aws-sdk/s3-request-presigner';+import {AwsRegion, getAwsClient} from '@remotion/lambda/client';++const generatePresignedUrl = async ({+ contentType,+ contentLength,+ expiresIn,+ bucketName,+ region,+}: {+ contentType: string;+ contentLength: number;+ expiresIn: number;+ bucketName: string;+ region: AwsRegion;+}): Promise<{presignedUrl: string; readUrl: string}> => {+ if (contentLength > 1024 * 1024 * 200) {+ throw new Error(+ `File may not be over 200MB. Yours is ${contentLength} bytes.`,+ );+ }++ const {client, sdk} = getAwsClient({+ region: process.env.REMOTION_AWS_REGION as AwsRegion,+ service: 's3',+ });++ const key = crypto.randomUUID();++ const command = new sdk.PutObjectCommand({+ Bucket: bucketName,+ Key: key,+ ACL: 'public-read',+ ContentLength: contentLength,+ ContentType: contentType,+ });++ const presignedUrl = await getSignedUrl(client, command, {+ expiresIn,+ });++ // The location of the asset after the upload+ const readUrl = `https://${bucketName}.s3.${region}.amazonaws.com/${key}`;++ return {presignedUrl, readUrl};+};++export const POST = async (request: Request) => {+ if (!process.env.REMOTION_AWS_BUCKET_NAME) {+ throw new Error('REMOTION_AWS_BUCKET_NAME is not set');+ }++ if (!process.env.REMOTION_AWS_REGION) {+ throw new Error('REMOTION_AWS_REGION is not set');+ }++ const json = await request.json();+ if (!Number.isFinite(json.size)) {+ throw new Error('size is not a number');+ }+ if (typeof json.contentType !== 'string') {+ throw new Error('contentType is not a string');+ }++ const {presignedUrl, readUrl} = await generatePresignedUrl({+ contentType: json.contentType,+ contentLength: json.size,+ expiresIn: 60 * 60 * 24 * 7,+ bucketName: process.env.REMOTION_AWS_BUCKET_NAME as string,+ region: process.env.REMOTION_AWS_REGION as AwsRegion,+ });++ return NextResponse.json({presignedUrl, readUrl});+};+```++This is how you can call it in the frontend:++```tsx twoslash title="Uploader.tsx"+// @module: es2022+// @target: es2017+const file: File = {} as unknown as File;+// ---cut---+const presignedResponse = await fetch('/api/upload', {+ method: 'POST',+ body: JSON.stringify({+ size: file.size,+ contentType: file.type,+ // ^?+ }),+});++const json = (await presignedResponse.json()) as {+ presignedUrl: string;+ readUrl: string;+};+```++:::note+This example does not implement any rate limiting or authentication.+:::++## Performing the Uploading++### Using fetch()Send the presigned URL back to the client. Afterwards, you can now perform an upload using the built-in [`fetch()`](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) function:-```ts twoslash title="App.tsx"+```ts twoslash title="upload-with-fetch.ts"// @module: ESNext// @target: ESNext-import { interpolate } from "remotion";-const presignedUrl = "hi";+import {interpolate} from 'remotion';+const presignedUrl = 'hi';const file: File = {} as unknown as File;-const contentType = file.type || "application/octet-stream";+const contentType = file.type || 'application/octet-stream';const arrayBuffer = await file.arrayBuffer();// ---cut---await fetch(presignedUrl, {- method: "PUT",+ method: 'PUT',body: arrayBuffer,headers: {- "content-type": contentType,+ 'content-type': contentType,},});```+### Tracking the upload progress++As of October 2024, if you need to track the progress of the upload, you need to use [`XMLHTTPRequest`](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest).++```ts twoslash title="upload-with-progress.ts"+export type UploadProgress = {+ progress: number;+ loadedBytes: number;+ totalBytes: number;+};++export type OnUploadProgress = (options: UploadProgress) => void;++export const uploadWithProgress = ({+ file,+ url,+ onProgress,+}: {+ file: File;+ url: string;+ onProgress: OnUploadProgress;+}): Promise<void> => {+ return new Promise((resolve, reject) => {+ const xhr = new XMLHttpRequest();++ xhr.open('PUT', url);++ xhr.upload.onprogress = function (event) {+ if (event.lengthComputable) {+ onProgress({+ progress: event.loaded / event.total,+ loadedBytes: event.loaded,+ totalBytes: event.total,+ });+ }+ };++ xhr.onload = function () {+ if (xhr.status === 200) {+ resolve();+ } else {+ reject(new Error(`Upload failed with status: ${xhr.status}`));+ }+ };++ xhr.onerror = function () {+ reject(new Error('Network error occurred during upload'));+ };++ xhr.setRequestHeader('content-type', file.type);+ xhr.send(file);+ });+};+```+## See also- [Handling user video uploads](/docs/video-uploads)