I have a Next.js 13 api route which is supposed to be able to write a list of users to a file. I also have a route which reads from the users json file.
const USERS_FILE_PATH = join(process.cwd(), '/tmp', 'data.json');
fs.writeFileSync(POSTS_FILE_PATH, JSON.stringify(users));
On my local machine, I'm able to read and write the file, but when I deploy with Vercel I can read but writing throws this error:
EROFS: read-only file system, open '/var/task/tmp/data.json'
I saw here that using the '/tmp' folder is a workaround I can use, but it is still not working. Any help would be appreciated.
You are not writing to /tmp
, you are writing to ./tmp
(as the error says: /var/task/tmp
in your case). The whole issue is that your application directory is not writable (which is a good thing - you don't want something to be able to modify your application other than through a new deployment), so as long as you make your path relative to that, writing there still won't work.
Remove process.cwd()
from the path.join
:
const USERS_FILE_PATH = join('/tmp', 'data.json');
However, this still sounds like a flaky solution, because as soon as AWS destroys your execution environment (when it wasn't used for a bit, for example), your data will be gone. Additionally, when you have more traffic and AWS will scale up your function by creating multiple parallel execution environments, suddenly it will be random which request "sees" which data, because each of the instances will have their own version of it! Instead, you need to use a database for persistence, not a local file.