next.js

Uploadthing deleting files


How can I delete files from UploadThing? (NextJS 13)

Currently I try it like this:

-> src/server/delete.ts

import { UTApi } from "uploadthing/server"

export const utapi = new UTApi();

-> src/server/deleteImage.js

import React from 'react'
import { utapi } from './delete'

const deleteImage = () => {

    const testDelete = async () => {
        console.log("delete files")
        const res = await utapi.deleteFiles("b0e3a5bc-dd85-40fe-9a0c-59d2ece0bb60-4ulhix.png");
        console.log(res)
    }

    return (
        <div>
            <h1>test image delete</h1>
            <button onClick={testDelete}>Delete files</button>
        </div>
    )
}

export default deleteImage

I then try to call it from a client component like this:

<DeleteImage />

However, I get the error: "Uncaught (in promise) Error: The utapi can only be used on the server."

Are there any good examples on how to delete files on uploadthing?

Thanks in advance!


Solution

  • It worked for me:

      export const { GET, POST } = createNextRouteHandler({
      router: ourFileRouter,
    });
    
    export async function DELETE(request: Request) {
      const data = await request.json();
      const newUrl = data.url.substring(data.url.lastIndexOf("/") + 1);
      const utapi = new UTApi(); --- i used this inside route file in uploadthing folder
      await utapi.deleteFiles(newUrl);
    
      return Response.json({ message: "ok" });
    }
    

    this is my delete function in client component:

    const deleteValue = async () => {
        await axios.delete("api/uploadthing", {
          data: {
            url: value,
          },
        });
      };