Create upload files api in next.js

You can upload files with Next.js API routes.

Example with default Next.js body parse

API handler

export default (req, res) => {
  // req.body contains a content of an uploaded file + headers
}

req.body is a string that contains related HTTP headers in the beginning like

------WebKitFormBoundarydj2uhBXPZtD3nte3
Content-Disposition: form-data; name="your_input_name"; filename="your_file_name.json"
Content-Type: application/json
your file content is here!

So, you would need to take out the content from it. Probably there are some packages that can do it.

Alternatively, you can parse the request with a third-party package.

Example with formidable

API handler

import { IncomingForm } from 'formidable'
// you might want to use regular 'fs' and not a promise one
import { promises as fs } from 'fs'

// first we need to disable the default body parser
export const config = {
  api: {
    bodyParser: false,
  }
};

export default async (req, res) => {
  // parse form with a Promise wrapper
  const data = await new Promise((resolve, reject) => {
    const form = new IncomingForm()
    
    form.parse(req, (err, fields, files) => {
      if (err) return reject(err)
      resolve({ fields, files })
    })
  })

  // read file from the temporary path
  const contents = await fs.readFile(data?.files?.nameOfTheInput.path, {
    encoding: 'utf8',
  })

  // contents is a string with the content of uploaded file, so you can read it or store
}

Code in the examples above for the illustration purpose only. At least need to wrap it in try catch statement with proper error handling.

Tags:

Next.Js