vercel / storage

Vercel Postgres, KV, Blob, and Edge Config
https://vercel.com/storage
Apache License 2.0
516 stars 57 forks source link

onUploadCompleted not triggered in vercel deploiement #687

Open JeremCy opened 5 months ago

JeremCy commented 5 months ago

Package.json info: "next": "14.2.3", "@vercel/blob": "^0.23.3"

Hello, I was developing a open application form for my application, when i test it using ngrok the onUploadCompleted is triggered and update my job application table.

When i try the same test in the vercel environement the create job application and the upload is working, but not the update to cv_url column.

form action function:

async function action(data: z.infer<typeof schema>) {
    try {
      setLoading(true);
      const file = data.cv;
      const fileNames = file.name;
      const apiCall = await CreateCandidature(data);
      if (apiCall.status === 201) {
        let candidature: Candidature = await apiCall.json();
        await upload(fileNames, file, {
          access: "public",
          handleUploadUrl: "/api/cv/upload",
          clientPayload: candidature.id.toString(),
        });
        toast({
          title: "Candidature created",
          description: "Candidature has been created successfully",
        });
        setLoading(false);
        form.reset();
      } else {
        setLoading(false);
        toast({
          title: "Error",
          description: "An error has occurred",
        });
      }
    } catch (error) {
      setLoading(false);
      console.error(error);
      toast({
        title: "Error",
        description: "An error has occurred",
      });
    }
  }

my upload route:

export async function POST(request: Request): Promise<NextResponse> {
  const body = (await request.json()) as HandleUploadBody;
  try {
    const jsonResponse = await handleUpload({
      body,
      request,
      onBeforeGenerateToken: async (pathname, clientPayload) => {
        // Generate a client token for the browser to upload the file
        // ⚠️ Authenticate and authorize users before generating the token.
        // Otherwise, you're allowing anonymous uploads.

        return {
          allowedContentTypes: [
            "application/pdf",
          ],
          tokenPayload: JSON.stringify({
            pathname,
            clientPayload,
          }),
        };
      },
      onUploadCompleted: async ({ blob, tokenPayload }) => {
        // Get notified of client upload completion
        // ⚠️ This will not work on `localhost` websites,
        // Use ngrok or similar to get the full upload flow

        console.log("blob upload completed", blob, tokenPayload);
        try {
          // Run any logic after the file upload completed
          //update candidature
          if (!tokenPayload) throw new Error("No token payload found");
          const payload = JSON.parse(tokenPayload);
          console.info("Updating candidature payload=" + payload);
          !payload?.clientPayload
            ? console.error("No client payload found")
            : console.info("Client payload found");
          const candidature = await prisma.candidature.update({
            where: { id: Number(payload.clientPayload) },
            data: {
              cv: blob.url,
            },
          });
          console.info("Candidature updated", candidature);
        } catch (error) {
          console.error("Error updating candidature", error);
          throw new Error("Could not update candidature");
        }
      },
    });

    return NextResponse.json(jsonResponse);
  } catch (error) {
    return NextResponse.json(
      { error: (error as Error).message },
      { status: 400 }, // The webhook will retry 5 times waiting for a 200
    );
  }
}
LFVH commented 2 months ago

Hi! I've just had a problem where blob was uploaded but onUploadCompleted would not trigger so I've tried the same "happy path" with another domain (assigned to my deployment by vercel) and it has worked :D

voldmar commented 2 months ago

Hey,

I have the same problem. Do you have Vercel Authentication for deployments protection turned on?

JeremCy commented 2 months ago

Hey @voldmar, Yes I have the Vercel Authentication for deployments protection turned on.

voldmar commented 2 months ago

@JeremCy Looks like it blocks the callbacks. I am making all the callback stuff after the upload