pingdotgg / uploadthing

File uploads for modern web devs
https://uploadthing.com
MIT License
4.07k stars 302 forks source link

[bug]: Blocked by CORS policy. No 'Access-Control-Allow-Origin' header is present on the requested resource. #962

Open codesbyhusnain opened 3 days ago

codesbyhusnain commented 3 days ago

Provide environment information

System:
    OS: macOS 15.0
    CPU: (8) arm64 Apple M2
    Memory: 79.98 MB / 8.00 GB
    Shell: 5.9 - /bin/zsh
  Binaries:
    Node: 20.16.0 - ~/.nvm/versions/node/v20.16.0/bin/node
    npm: 10.8.1 - ~/.nvm/versions/node/v20.16.0/bin/npm
    bun: 1.1.24 - ~/.bun/bin/bun
  Browsers:
    Chrome: 128.0.6613.138
    Safari: 18.0
  npmPackages:
    @uploadthing/react: ^7.0.2 => 7.0.2 
    typescript: ^5 => 5.6.2 
    uploadthing: ^7.0.2 => 7.0.2

Describe the bug

I am using Next.js App router in my project and uploadthing to handle my image and video upload. I followed the documentation exactly as on the website.

This is my api/uploadthing/core.ts:

import { auth } from "@clerk/nextjs/server";
import { createUploadthing, type FileRouter } from "uploadthing/next";
import { UploadThingError } from "uploadthing/server";

const f = createUploadthing();

const handleAuth = () => {
  // Authentication logic
  const { userId } = auth();
  if (!userId) throw new UploadThingError("Unauthorized");
  return { userId };
};

// FileRouter for your app, can contain multiple FileRoutes
export const ourFileRouter = {
  courseImage: f({ image: { maxFileSize: "16MB", maxFileCount: 1 } })
    .onUploadComplete(() => { console.log("Complete")}),

  courseAttachment: f(["text", "image", "video", "audio", "pdf"])
    .middleware(() => handleAuth())
    .onUploadComplete(() => {}),

  chapterVideo: f({ video: { maxFileCount: 1, maxFileSize: "512GB" } })
    .middleware(() => handleAuth())
    .onUploadComplete(() => {}),
} satisfies FileRouter;

export type OurFileRouter = typeof ourFileRouter;

This is my route.ts: import { createRouteHandler } from "uploadthing/next";

import { ourFileRouter } from "./core";

// Export routes for Next App Router
export const { GET, POST } = createRouteHandler({
  router: ourFileRouter,

  // Apply an (optional) custom config:
  // config: { ... },
});

This is my lib/uploadthing.ts:

import {
  generateUploadButton,
  generateUploadDropzone,
} from "@uploadthing/react";

import type { OurFileRouter } from "@/app/api/uploadthing/core";

export const UploadButton = generateUploadButton<OurFileRouter>();
export const UploadDropzone = generateUploadDropzone<OurFileRouter>();

I am getting this error when I try to upload an image

Screenshot 2024-09-19 at 5 50 08β€―AM

Link to reproduction

https://stackblitz.com/github/pingdotgg/uploadthing/tree/main/examples/minimal-appdir?file=README.md

To reproduce

Follow the steps I mentioned in my bug to reproduce this issue.

Additional information

No response

πŸ‘¨β€πŸ‘§β€πŸ‘¦ Contributing

Code of Conduct

juliusmarminge commented 3 days ago

hey sorry for this. we're aware and working on nailing down the issue.

if you don't mind me asking, do you see this for all uploads, or just some? Any correlation in file upload size to when it errors? Our current working theory is that this is more likely to happen for very small files

codesbyhusnain commented 2 days ago

I tried uploading 2 different files. 1 was 5 MB and the other was 2 KB. I ran into this error on both occasions. I don't think it has anything to do with filesize. Maybe CORS settings on your receiving end.

juliusmarminge commented 2 days ago

can you provide the file keys for keys that fails?

fyi, the cors error is a "false"/inaccurate error of what's happening, you should not hit a 504 in the first place

juliusmarminge commented 2 days ago

Hey @codesbyhusnain, I believe a fix has been deployed to our staging infra.

If you would like to help us confirm before shipping to prod, reach out to me on discord and I'll provide you with a token you can test with.

If not, no worries. I can ping here when the fix has been promoted to production

mehrdadrafiee commented 2 days ago

running into the same issue. I'll wait until the fix propagates to all servers 🀞

mehrdadrafiee commented 1 day ago

is this fixed? I'm able to upload (I see the uploaded file in my uploadthing dashboard) but I still get this error message.

juliusmarminge commented 1 day ago

Just promoted the fix to production deployments.

Please let me know if the issue persists after giving it a go

mehrdadrafiee commented 1 day ago

@juliusmarminge thanks! looks like the CORS error is gone now, however, I'm getting a 404 error now and am not able to upload.

GET http://localhost:3000/api/uploadthing 404 (Not Found)
// /api/uploadthing/core.ts

import { currentUser } from "@clerk/nextjs/server";
import { createUploadthing, type FileRouter } from "uploadthing/next";
import { UploadThingError } from "uploadthing/server";

const f = createUploadthing();

const getUser = async () => await currentUser();

// FileRouter for your app, can contain multiple FileRoutes
export const ourFileRouter = {
  // Define as many FileRoutes as you like, each with a unique routeSlug
  imageUploader: f({ image: { maxFileSize: "4MB", maxFileCount: 1 } })
    // Set permissions and file types for this FileRoute
    .middleware(async ({ req }) => {
      // This code runs on your server before upload
      const user = await getUser();

      // If you throw, the user will not be able to upload
      if (!user) throw new UploadThingError("Unauthorized");

      // Whatever is returned here is accessible in onUploadComplete as `metadata`
      return { userId: user.id };
    })
    .onUploadComplete(async ({ metadata, file }) => {
      // This code RUNS ON YOUR SERVER after upload
      console.log("Upload complete for userId:", metadata.userId);

      console.log("file url", file.url);

      // !!! Whatever is returned here is sent to the clientside `onClientUploadComplete` callback
      return { uploadedBy: metadata.userId };
    }),
} satisfies FileRouter;

export type OurFileRouter = typeof ourFileRouter;
// /api/uploadthing/route.ts

import { createRouteHandler } from "uploadthing/next";

import { ourFileRouter } from "./core";

export const { GET, POST } = createRouteHandler({ router: ourFileRouter });

I followed the documentation. anything I'm missing here?

juliusmarminge commented 1 day ago

maybe you're running some other server on port 3000?

mehrdadrafiee commented 1 day ago

killed all processes running on port 3000 and re-ran the app but still getting the 404 error:

button-client-Chdyu4qo.js:115 

GET http://localhost:3000/api/uploadthing 404 (Not Found)

running the app on a different port is not helping either πŸ€·β€β™‚οΈ

juliusmarminge commented 1 day ago

I mean we haven't changed anything on the package side so if that part worked before it's something on your machine πŸ€·β€β™‚οΈ restart system maybe?

butadpj commented 1 day ago

Hi, I just encounteted the same issue today

Access to XMLHttpRequest at 'https://sea1.ingest.uploadthing.com/sREXOvoL8YcFXk9s7GrwE0iblNId7JnGZtx8M32jehg6RpLz?expires=1726914551940&x-ut-identifier=wau16cs4n9&x-ut-file-name=Screenshot%25202024-08-25%2520at%252010.42.45%25E2%2580%25AFPM.png&x-ut-file-size=469011&x-ut-file-type=image%252Fpng&x-ut-slug=imageUploader&x-ut-content-disposition=inline&signature=hmac-sha256%3D8d6467592330d4777f01f018cf99d6fb2992e39feed08039946eee53cb5929f3' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.Understand this error

Uploads are failing on the client side but the uploaded fiels are in my UT dashboard

onUploadError() is being triggered while onClientUploadComplete() is not

codezeloss commented 1 day ago

Hi, I just encounteted the same issue today

Access to XMLHttpRequest at 'https://sea1.ingest.uploadthing.com/sREXOvoL8YcFXk9s7GrwE0iblNId7JnGZtx8M32jehg6RpLz?expires=1726914551940&x-ut-identifier=wau16cs4n9&x-ut-file-name=Screenshot%25202024-08-25%2520at%252010.42.45%25E2%2580%25AFPM.png&x-ut-file-size=469011&x-ut-file-type=image%252Fpng&x-ut-slug=imageUploader&x-ut-content-disposition=inline&signature=hmac-sha256%3D8d6467592330d4777f01f018cf99d6fb2992e39feed08039946eee53cb5929f3' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.Understand this error

Uploads are failing on the client side but the uploaded fiels are in my UT dashboard

onUploadError() is being triggered while onClientUploadComplete() is not

Same problemπŸ’―! It's just keep loading after a successful upload, but instead of getting the right response, I got the same error as yours above!!

alexfung888 commented 21 hours ago

All my angular fire applications that uses Google federation for authentication now fail with chrome:

Access to fetch at 'https://securetoken.googleapis.com/v1/token?key=xxx' from origin 'http://localhost:4400' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

they no no matter whether they are localhost or real production URL. Works fine on Chrome yesterday. Now fails with Chrome 128.0.6613.138 and 129.0.6668.59. Still works fine on Edge.

And I cannot access Feedly anymore, because I login my account using Google federation. I guess everything that rides Login using Google is now dead on Chrome.

butadpj commented 11 hours ago

Oh god. I just realized I have this condition in my clerkMiddleware() that protects all routes except to routes in my isPublicRoute route matcher. So, if you're using Clerk on your auth, make sure you don't protect the entire "/api/uploadthing" as mentioned in the docs

image