naystack - v1.9.9
    Preparing search index...

    Function setupFileUpload

    • Configures file upload for S3. Returns a PUT route handler (for the client to upload files) and server-side helpers.

      Mount the PUT handler on your file upload API route (e.g. app/api/(rest)/file/route.ts). The client can then use useFileUpload() from naystack/file/client to upload files with the auth token.

      AWS credentials are read from env vars: S3_ACCESS_KEY_ID, S3_ACCESS_KEY_SECRET, S3_REGION, S3_BUCKET.

      Parameters

      Returns {
          PUT: (
              req: NextRequest,
          ) => Promise<
              | NextResponse<{ error: string }>
              | NextResponse<{ onUploadResponse: object; url: string }>,
          >;
      }

      Object with:

      • PUT — Next.js route handler for file uploads (auth required, multipart form).
      • uploadFile(keys, { url?, blob? }) — Server-side: upload a file from URL or Blob to S3.
      • deleteFile(url) — Server-side: delete a file by its S3 URL.
      • getUploadURL(keys) — Server-side: get a presigned PUT URL (5-minute expiry).
      • getDownloadURL(keys) — Get the public download URL for a key.
      // app/api/(rest)/file/route.ts
      import { setupFileUpload } from "naystack/file";

      export const { PUT } = setupFileUpload({
      onUpload: async ({ url, type, userId, data }) => {
      if (type === "DealDocument" && url) {
      // `data` is absent unless the client sent one — check before reading it.
      const payload = data as { dealId?: number; fileName?: string } | undefined;
      if (!payload?.dealId) return {};
      const [row] = await db.insert(DocumentsTable).values({
      dealId: payload.dealId, fileURL: url, fileName: payload.fileName,
      }).returning();
      return row ?? {};
      }
      return {};
      },
      // Optional: customize the S3 key (defaults to UUID)
      getKey: async ({ type, userId }) => `${type}/${userId}/${crypto.randomUUID()}`,
      });