Theo's Typesafe CultTTC
Theo's Typesafe Cult3y ago
11 replies
wlvz

405 Error with S3 Presigned URL's

I currently have a 'PDF viewer' on my website which is suppose to render a PDF from my s3 bucket and prevent the user from being able to download, print, etc the pdf.

Here's the code for the /exams/page.tsx file (the PDF viewer)
"use client";
import React, { useState, useEffect } from "react";

const PDFViewer = (presignedUrl: RequestInfo | URL) => {
  const [pdfUrl, setPdfUrl] = useState("");

  useEffect(() => {
    const fetchPdf = async () => {
      try {
        const objectKey = "biology/Photosynthesis 1.pdf";
        const response = await fetch(`/api/exams?objectKey=${objectKey}`);
        const pdfObjectUrl = URL.createObjectURL(await response.blob());
        setPdfUrl(pdfObjectUrl);
      } catch (error) {
        console.error("Error fetching PDF:", error);
      }
    };

    fetchPdf();

    return () => {
      if (pdfUrl) {
        URL.revokeObjectURL(pdfUrl);
      }
    };
  }, []);

  const handleContextMenu = (
    event: React.MouseEvent<HTMLDivElement, MouseEvent>
  ) => {
    event.preventDefault();
  };

  const handleMouseDown = (
    event: React.MouseEvent<HTMLDivElement, MouseEvent>
  ) => {
    if (event.button === 2) {
      event.preventDefault();
    }
  };

  return (
    <div
      className="fixed inset-0 flex items-center justify-center"
      onContextMenu={handleContextMenu}
      onMouseDown={handleMouseDown}
    >
      <div className="absolute inset-0 bg-gray-900 opacity-75 pointer-events-none" />
      <div className="relative w-full h-full flex items-center justify-center">
        {pdfUrl ? (
          <embed
            src={`${pdfUrl}#toolbar=0`}
            type="application/pdf"
            className="w-full h-full"
            onContextMenu={handleContextMenu}
          />
        ) : (
          <p>Loading PDF...</p>
        )}
      </div>
    </div>
  );
};

export default PDFViewer;

(continued because im running out of characters)
Was this page helpful?