Theo's Typesafe CultTTC
Theo's Typesafe Cult3y ago
2 replies
utdev

Delete file from s3 using presigned urls

I am trying to delete files from my bucket using a presigned url, so far this is my api handler:

import S3 from 'aws-sdk/clients/s3'
import { NextApiRequest, NextApiResponse } from 'next'


export default async function handler(
    req: NextApiRequest,
    res: NextApiResponse
) {

    const s3 = new S3({
        signatureVersion: 'v4',
        region: process.env.REGION,
        accessKeyId: process.env.AWS_ACCESS_KEY,
        secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
    })

    console.log("the passed query", req.query.key)

    const url = await s3.getSignedUrlPromise('deleteObject', {
        Bucket: process.env.BUCKET_NAME,
        Key: req.query.key as string,
    })

    res.status(200).json({
        url
    })
}


In my frontend I am doing this:

const GalleryDetailsSidebar = ({
  selectedFile,
  refetchFiles,
}: GalleryDetailsSidebarProps) => {
  const { url } = usePresignedUrl(selectedFile.key)
  const {
    isLoading,
    isSuccess,
    mutate: deleteTemplate,
  } = api.file.delete.useMutation()

  const handleDelete = async () => {
    await deleteTemplate({
      id: selectedFile.id,
    })

    if (isSuccess) {
      refetchFiles()
    }

    const { url, status } = await fetch(
      `/api/file/delete?key=${selectedFile.key}`
    )

    const response = await fetch(url, {
      method: 'DELETE',
      headers: {
        'Content-Type': 'application/json',
      },
    }).then((res) => res.json())

    console.log('response', response.url)

    if (response.status === 200) {
      console.log('deleted from db')
    }
  }


I am able to delete the file from my database, but not from my bucket not sure what I am missing, I should have the properly policy in my bucket.
Was this page helpful?