t3: accessing static files server side

I'm trying to use fs.readFileSync to read PDFs and font files (.ttf) on the server (to dynamically build a PDF report in response to an API call), but I get ENOENT: no such file or directory no matter what I do. Even when the static file is in the same directory as the code trying to access it, I can't seem to target it. I noticed that __dirname targets /.next/server/app/api/trpc/[trpc] rather than the server-side file system, so I haven't been able to use it to help solve this problem. I feel like I must be missing something obvious, but I haven't found the answer yet.
Solution:
try using process.cwd() instead of __dirname reference: https://github.com/vercel/next.js/discussions/14341 in which dir have you stored those pdf and font files...
GitHub
__dirname pointing to / (during dev) · vercel next.js · Discussio...
I'm trying to port some code to Next, and I'd say I was pretty familiar with how everything works, but this has stumped me (and there doesn't seem to be a mention in these discussions) ...
Jump to solution
2 Replies
Solution
webdevkaleem
webdevkaleem2w ago
try using process.cwd() instead of __dirname reference: https://github.com/vercel/next.js/discussions/14341 in which dir have you stored those pdf and font files i am assuming those files are stored inside your dir on build time as nextjs on vercel only allows temporary / ephemeral storage
GitHub
__dirname pointing to / (during dev) · vercel next.js · Discussio...
I'm trying to port some code to Next, and I'd say I was pretty familiar with how everything works, but this has stumped me (and there doesn't seem to be a mention in these discussions) ...
Sienna
SiennaOP2w ago
process.cwd() was the fix, thanks! I'm now able to use code like these examples to reference files in the /public directory as well as files in /src/server.
const pdf = fs.readFileSync(
path.join(
process.cwd(),
`/src/server/pdf/example.pdf`,
),
);
const font = fs.readFileSync(
path.join(process.cwd(), "/public/font.otf"),
);
const pdf = fs.readFileSync(
path.join(
process.cwd(),
`/src/server/pdf/example.pdf`,
),
);
const font = fs.readFileSync(
path.join(process.cwd(), "/public/font.otf"),
);

Did you find this page helpful?