Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: file uploads #807

Draft
wants to merge 15 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ NEXT_PUBLIC_POSTHOG_HOST="https://eu.i.posthog.com" # Probably, if your Posthog
NEXT_PUBLIC_AXIOM_DATASET="..." # Is the name of the Axiom dataset where you want to send data.
NEXT_PUBLIC_AXIOM_TOKEN="..." # Is the Axiom API token you have generated.

# Uploadthing
UPLOADTHING_TOKEN="..."

# Enviroment variables that Convex will automatically set up for you
CONVEX_DEPLOYMENT="dev:..."
Expand Down
4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,8 @@
"@sentry/nextjs": "^8",
"@serwist/next": "9.0.11",
"@t3-oss/env-nextjs": "^0.12.0",
"babel-plugin-react-compiler": "19.0.0-beta-e552027-20250112",
"@uploadthing/react": "^7.1.5",
"babel-plugin-react-compiler": "19.0.0-beta-714736e-20250131",
"class-variance-authority": "^0.7.0",
"clsx": "^2.1.1",
"convex": "^1.19.0",
Expand Down Expand Up @@ -65,6 +66,7 @@
"sonner": "^1.7.0",
"tailwind-merge": "^3.0.0",
"tailwindcss-animate": "^1.0.7",
"uploadthing": "^7.4.4",
"zod": "^3.23.8"
},
"devDependencies": {
Expand Down
192 changes: 161 additions & 31 deletions pnpm-lock.yaml

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion src/app/api/sign-up/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ export async function OPTIONS(request: Request) {
}
}

// TODO: This probably deserves a rate limiter + a check for not creating a bunch of trash users to spam us.
// TODO: This deserves a rate limiter + a check for not creating a bunch of trash users to spam us. Example: https://github.com/t3dotgg/t3gallery/blob/main/src/server/ratelimit.ts
export async function POST(request: Request) {
const unparsedSignUpHeaders = (await request.json()) as FormSchemaSignUp;
const parsedSignUpHeaders = formSchemaSignUp.safeParse(unparsedSignUpHeaders);
Expand Down
58 changes: 58 additions & 0 deletions src/app/api/uploadthing/core.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import { auth } from "@clerk/nextjs/server";
import { log } from "next-axiom";
import { createUploadthing, type FileRouter } from "uploadthing/next";
import { UploadThingError } from "uploadthing/server";

const f = createUploadthing();

// FileRouter for your app, can contain multiple FileRoutes
export const ourFileRouter = {
// Define as many FileRoutes as you like, each with a unique routeSlug
fileUploader: f({
image: {
/**
* For full list of options and defaults, see the File Route API reference
* @see https://docs.uploadthing.com/file-routes#route-config
*/
maxFileSize: "4MB",
maxFileCount: 20,
},
video: {
maxFileSize: "16MB",
maxFileCount: 5,
},
blob: {
maxFileSize: "8MB",
maxFileCount: 20,
},
})
// Set permissions and file types for this FileRoute
.middleware(async () => {
// This code runs on your server before upload
const user = await auth();

// If you throw, the user will not be able to upload
if (!user.userId)
// eslint-disable-next-line @typescript-eslint/only-throw-error
throw new UploadThingError({
message: "Unauthorized",
code: "FORBIDDEN",
});

// TODO: This deserves a rate limiter + a check for not creating a bunch of trash files to spam us. Example: https://github.com/t3dotgg/t3gallery/blob/main/src/server/ratelimit.ts

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

// TODO: Call Convex to store the file in the db

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

export type OurFileRouter = typeof ourFileRouter;
10 changes: 10 additions & 0 deletions src/app/api/uploadthing/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
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: { ... },
});
12 changes: 12 additions & 0 deletions src/app/layout.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import "~/styles/globals.css";
import { ClerkProvider } from "@clerk/nextjs";
import { NextSSRPlugin } from "@uploadthing/react/next-ssr-plugin";
import { ourFileRouter } from "~/app/api/uploadthing/core";
import ConvexClientProvider from "~/app/convex-client-provider";
import { ThemeProvider } from "~/components/theme-provider";
import { Toaster } from "~/components/ui/sonner";
Expand All @@ -11,6 +13,7 @@ import Script from "next/script";
import { NuqsAdapter } from "nuqs/adapters/next/app";
import React from "react";
import { Monitoring } from "react-scan/monitoring/next";
import { extractRouterConfig } from "uploadthing/server";
import { CSPostHogProvider } from "./_analytics/provider";

const APP_NAME = "Chat.io";
Expand Down Expand Up @@ -89,6 +92,15 @@ export default function RootLayout({
// eslint-disable-next-line no-restricted-properties
branch={process.env.NEXT_PUBLIC_VERCEL_GIT_COMMIT_REF}
/>
<NextSSRPlugin
/**
* The `extractRouterConfig` will extract **only** the route configs
* from the router to prevent additional information from being
* leaked to the client. The data passed to the client is the same
* as if you were to fetch `/api/uploadthing` directly.
*/
routerConfig={extractRouterConfig(ourFileRouter)}
/>
<ThemeProvider
attribute="class"
defaultTheme="system"
Expand Down
12 changes: 12 additions & 0 deletions src/lib/uploadthing.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import {
generateReactHelpers,
generateUploadButton,
generateUploadDropzone,
} from "@uploadthing/react";
import type { OurFileRouter } from "~/app/api/uploadthing/core";

export const { useUploadThing, uploadFiles, createUpload, getRouteConfig } =
generateReactHelpers<OurFileRouter>();

export const UploadButton = generateUploadButton<OurFileRouter>();
export const UploadDropzone = generateUploadDropzone<OurFileRouter>();
5 changes: 3 additions & 2 deletions tailwind.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,9 @@ import type { PluginCreator } from "postcss";
import type { Config } from "tailwindcss";
// @ts-expect-error - Tailwind CSS does not have types for this package unfortunately
import { default as flattenColorPalette } from "tailwindcss/lib/util/flattenColorPalette";
import { withUt } from "uploadthing/tw";

const config = {
const config = withUt({
darkMode: ["class"],
content: [
"./pages/**/*.{ts,tsx}",
Expand Down Expand Up @@ -93,7 +94,7 @@ const config = {
},
// eslint-disable-next-line @typescript-eslint/no-require-imports
plugins: [require("tailwindcss-animate"), addVariablesForColors],
} satisfies Config;
} satisfies Config);

// This plugin adds each Tailwind color as a global CSS variable, e.g. var(--gray-200).
function addVariablesForColors({
Expand Down