Next.js Discord

Discord Forum

Importing files

Unanswered
Birman posted this in #help-forum
Open in Discord
BirmanOP
is there a way to import files other than images in my code? like suppose i want the user to be able to download a pdf after they paid for it. i don't want the pdf to be static ofc otherwise they can just navigate to the public link and get it

23 Replies

Save the file as part of your codebase and then use fs.readFileSync(path.resolve(process.cwd(), “src/file.pdf”))
To load it as a buffer or some raw text
Then you can redirect the user to a download it
By setting the content headers
In your response
It’s called the content disposition header
And you can define the file name in it
Just google all these terms I mentioned
And you’ll get a solution
@Birman ^
@linesofcode <@330826222928134144> ^
BirmanOP
thank you. i'll try to implement a solution based on that. i was wondering though if there was a way to actually import the file in my code with an import statement and let it be processed by webpack or something
You can technically do this for any file if if you write a webpack plugin for it
But it’s seldom what you want to do in the scenario you described above.
Otherwise there would have already been a loader for it configured
Like for importing mdx files
You can also consider storing all the files in s3 compatible store
And then generating a link to the file
With some expiration date
The downside here is that users could share pdf links with each other if the expiration time is long enough
Maybe not an issue for you.
@linesofcode Maybe not an issue for you.
BirmanOP
oh well this is for learning purposes mostly so i will probably experiment with multiple methods. i barely have any backend experience so it's kind of hard to understand what steps to take to do what
Ah okay
Good luck!