Google Document from your url (NextJS)
By default, Google Docs when you share the link brings the end user directly to the Google Docs.
This is fine, but sometimes we would need to have this link hidden. For any reason. They can be
different:
and you receive the link like:
https://docs.google.com/document/d/14uFMe_rPX7Bp83gMfE0lGMPRwUAW6jqkrfZZ8iBOCyJI/edit?usp=sharing
which by default bring you directly to the Google Document in View Mode. It is fine to share the link to someone who needs it but heard many times that it will be convenient to get this document already in PDF.
And Google already has this functionality which is described in Google Docs documentation.
But the link still looks long and visually it is on Google:
http://docs.google.com/presentation/d/<doc_id>/export/pdf
But we want to have it like:
https://your-domain.com/my-pdf
So how could we achieve it? That's easy. In NextJS we can create an API endpoint with the next code:
const response = await fetch(
`https://docs.google.com/document/d/<doc_id>/export/pdf`
)
const blob = await response.blob()
return new Response(blob, {
headers: {
'content-type': 'application/octet-stream',
'Content-Disposition': 'attachment; filename="Your_File.pdf"'
}
})
and that's all 🙂
almost...
Next.JS does the wonderful thing - it aggressively caches all the routes and pages to improve the performance of the app. In our case it will cache the API endpoint and the actual API call to the Google will be performed rarely. To avoid tis behaviour we should disable cache for the route:
export const revalidate = 0
Yes. This one line disables cache for the API route
Now when you will access this endpoint the browser will ask you to store the file in PDF format. The simple proxy to the Google Doc which makes the impression that this file is store on your resource
Google immediately stores the changes and makes them accessible