You don’t need to copy the PDF from S3 to your local filesystem to serve it securely. Instead, you can generate a temporary signed URL directly from S3, which allows authorized users to access the file for a limited time. This way, you avoid the hassle of managing local files and cleanup.
Here’s how you can do it in Laravel:
1. Generate a Temporary S3 URL
Assuming you’re using Laravel’s Filesystem (with S3 configured in config/filesystems.php):
use Illuminate\Support\Facades\Storage;
public function viewPdf($fileKey)
{
// Authorize the user here as needed
// Generate a temporary URL (valid for 5 minutes)
$url = Storage::disk('s3')->temporaryUrl(
$fileKey, now()->addMinutes(5)
);
// Redirect to the temporary URL, or return it as JSON for your frontend
return redirect($url);
}
2. Open in New Tab
On your frontend, have your "View PDF" button open the route in a new tab:
<a href="{{ route('pdf.view', ['fileKey' => $fileKey]) }}" target="_blank">View PDF</a>
Or, if you want to fetch the URL via AJAX and open it:
fetch('/pdf/view/{{ $fileKey }}')
.then(response => response.json())
.then(data => window.open(data.url, '_blank'));
And in your controller:
return response()->json(['url' => $url]);
3. No Need for Local Cleanup
Since you’re not storing anything locally, you don’t need to worry about cleaning up files. The signed URL will expire automatically.
Summary:
- Use
Storage::disk('s3')->temporaryUrl()to generate a short-lived, secure link to the PDF. - Serve that link to the user (either via redirect or JSON).
- Let the browser open it in a new tab.
- No need to copy files locally or manage cleanup.
Let me know if you need a more detailed code example!