Skip to content

How can i upload file using formidable with nextjs on vercel

api/upload.js

import formidable from 'formidable';

export const config = {
  api: {
    bodyParser: false,
  },
};

export default async (req, res) => {
  const form = new formidable.IncomingForm();
  form.uploadDir = "./";
  form.keepExtensions = true;
  form.parse(req, (err, fields, files) => {
    console.log(err, fields, files);
    res.send(err || "DONE")
  });
};

api/get.js

export default async (_, res) => {
    const fs = require('fs');
    fs.readdir("./", (err, files) => {
        console.log(err)
        res.send(err || files)
    });
};

Everything is working fine at localhost but it’s not working when i deploy it on vercel.

Function log from vercel dashboard

[POST] /api/upload

2021-02-21T12:47:11.662Z    f7bb8a02-2244-4d27-8a55-9e00a43b307b    ERROR   Uncaught Exception  {"errorType":"Error","errorMessage":"EROFS: read-only file system, open 'upload_2dd906bdebc97a1d63a371c9207b84be.png'","code":"EROFS","errno":-30,"syscall":"open","path":"upload_2dd906bdebc97a1d63a371c9207b84be.png","stack":["Error: EROFS: read-only file system, open 'upload_2dd906bdebc97a1d63a371c9207b84be.png'"]}
Unknown application error occurred

Answer

You need a server with file system access