> ## Documentation Index
> Fetch the complete documentation index at: https://docs.pyqdeck.in/llms.txt
> Use this file to discover all available pages before exploring further.

# File Upload System

> How PyqDeck handles PDF uploads using UploadThing

## Overview

PyqDeck uses **UploadThing** for handling file uploads. This service provides a secure way to upload files directly from the client (or via the backend) to a cloud storage provider (like AWS S3) without managing the infrastructure or complex multipart parsing yourself.

## Configuration

The system is configured in `backend/src/utils/uploadthing.js`.

### File Rules

* **Allowed Types**: `pdf` only.
* **Max File Size**: `16MB`.
* **Max File Count**: `1` per request.

## Upload Flow

The "pdfUploader" flow consists of two main stages:

### 1. Middleware (Pre-upload)

Before the file is sent to UploadThing, our server verifies the user's session using Clerk.

```javascript theme={null}
.middleware(async ({ req }) => {
  const user = req.auth;
  if (!user || !user.userId) throw new Error('Unauthorized');
  return { clerkId: user.userId };
})
```

The returned `clerkId` is stored as metadata and passed to the next stage.

### 2. onUploadComplete (Post-upload)

Once the file is successfully stored in UploadThing's cloud, they trigger a webhook back to our server.

* **Look up User**: We use the `clerkId` from the metadata to find the internal MongoDB `User` ID.
* **Save Record**: We create a new entry in the `Upload` collection in MongoDB.

## Data Model (`Upload.js`)

Each upload is tracked with the following fields:

* `url`: The public URL to access the file.
* `publicId`: The unique key provided by UploadThing (useful for deletions).
* `mimeType`: Always `application/pdf` for now.
* `size`: File size in bytes.
* `uploadedBy`: Reference to the `User` who performed the upload.

## Integration

Uploads are primarily used when creating or updating `Paper` records. The `Upload.id` is linked to the paper, allowing users to view the original PDF source.

## Environment Variables

| Variable             | Description                                |
| -------------------- | ------------------------------------------ |
| `UPLOADTHING_SECRET` | Secret key from the UploadThing dashboard. |
| `UPLOADTHING_APP_ID` | App ID from the UploadThing dashboard.     |
