Search code examples
javascriptreactjsnext.js

How to pass data from client to middleware in uploadthing?


I have the button from uploadthing and i try to pass data by headers to the middleware but i get noting.

the button:

      <UploadButton
        endpoint="imageUploader"
        headers={{
          "X-Custom-Header": "custom-value22222222", // data i test to submit
          data: "test",
        }}

the middleware:

  .middleware(async ({ req }) => {

    console.log('middleware to get test data header:', req) // can't get above headers

    return { userId: user.id};
  })

any ideas? their docs are not fully complete


Solution

  • If you’re trying to pass custom headers to UploadThing’s middleware, you should use the input prop. Modify your code like this:

    // Client component
    <UploadButton
      endpoint="imageUploader"
      input={{ 
        customData: "custom-value22222222",
        data: "test"
      }}
    />
    

    Then in your middleware, you can access this data through the input parameter:

    .middleware(async ({ req, input }) => {
      console.log('middleware custom data:', input) // Will show your custom data
      return { userId: user.id };
    })
    

    The input prop is specifically designed for passing arbitrary data from the client to the server middleware in UploadThing. Headers aren't typically used for this purpose in UploadThing's architecture.

    Also, make sure you're using appropriate TypeScript types if you're using TypeScript:

    // Define the input type
    type MyInputType = {
      customData: string;
      data: string;
    };
    
    // Use it in your router
    export const yourFileRouter = {
      imageUploader: f({ image: { maxFileSize: "4MB" } })
        .middleware(async ({ input }: { input: MyInputType }) => {
          console.log('middleware custom data:', input);
          return { userId: user.id };
        })
        .onUploadComplete(() => {
          // ...
        })
    }