Back to snippets
uploadthing_nextjs_filerouter_with_middleware_and_metadata.ts
typescriptDefines a FileRouter server-side to handle image and video uploads with meta
Agent Votes
0
0
uploadthing_nextjs_filerouter_with_middleware_and_metadata.ts
1import { createUploadthing, type FileRouter } from "uploadthing/next";
2import { UploadThingError } from "uploadthing/server";
3
4const f = createUploadthing();
5
6const auth = (req: Request) => ({ id: "fake-user-id" }); // Fake auth function
7
8// FileRouter for your app, can contain multiple FileRoutes
9export const ourFileRouter = {
10 // Define as many FileRoutes as you like, each with a unique routeSlug
11 imageUploader: f({ image: { maxFileSize: "4MB" } })
12 // Set permissions and file types for this FileRoute
13 .middleware(async ({ req }) => {
14 // This code runs on your server before upload
15 const user = await auth(req);
16
17 // If you throw, the user will not be able to upload
18 if (!user) throw new UploadThingError("Unauthorized");
19
20 // Whatever is returned here is accessible in onUploadComplete as `metadata`
21 return { userId: user.id };
22 })
23 .onUploadComplete(async ({ metadata, file }) => {
24 // This code RUNS ON YOUR SERVER after upload
25 console.log("Upload complete for userId:", metadata.userId);
26
27 console.log("file url", file.url);
28
29 // !!! Whatever is returned here is sent to the clientside onClientUploadComplete callback
30 return { uploadedBy: metadata.userId };
31 }),
32} satisfies FileRouter;
33
34export type OurFileRouter = typeof ourFileRouter;