Stevan Zečević
Stevan Zečević

Reputation: 31

How to create file from /api in NextJS?

I am currently trying to create a temp file from /api/sendEmail.js with fs.mkdirSync

fs.mkdirSync(path.join(__dirname, "../../public"));

but on Vercel (deployment platform) all folders are read-only and I can't create any temp files.

Error:

"errorMessage": "EROFS: read-only file system, mkdir '/var/task/.next/server/public'"

I have seen there are some questions about this but it's not clear, have any of you guys managed to do this?

Upvotes: 3

Views: 9163

Answers (1)

Adam Beleko
Adam Beleko

Reputation: 771

Vercel allows creation of files in /tmp directory. However, there are limitations with this. https://github.com/vercel/vercel/discussions/5320

An example of /api function that writes and reads files is:


import fs from 'fs';

export default async function handler(req, res) {
    const {
      method,
      body,
    } = req

    try {
      switch (method) {
        case 'GET': {
// read
          // This line opens the file as a readable stream
          const readStream = fs.createReadStream('/tmp/text.txt')

          // This will wait until we know the readable stream is actually valid before piping
          readStream.on('open', function () {
            // This just pipes the read stream to the response object (which goes to the client)
            readStream.pipe(res)
          })

          // This catches any errors that happen while creating the readable stream (usually invalid names)
          readStream.on('error', function (err) {
            res.end(err)
          })
          return
        }
        case 'POST':
          // write
          fs.writeFileSync('./test.txt', JSON.stringify(body))
          break
        default:
          res.setHeader('Allow', ['GET', 'POST'])
          res.status(405).end(`Method ${method} Not Allowed`)
      }
      // send result
      return res.status(200).json({ message: 'Success' })
    } catch (error) {
      return res.status(500).json(error)
    }
  }
}

Also see: https://vercel.com/support/articles/how-can-i-use-files-in-serverless-functions

Upvotes: 8

Related Questions