Comprehensive Guide to Handling FormData in Next.js with Client-Side and Server-Side Approaches

by Tajbin Khan Evan , Full Stack Developer

FormData is an essential part of modern web applications, allowing developers to handle form submissions effectively, especially when dealing with file uploads. In this guide, we’ll explore how to work with FormData in a Next.js application, both on the client side and server side, using the powerful Next.js app router..

Introduction to FormData

FormData is a built-in JavaScript object that can construct key/value pairs representing form fields and their values. This object is particularly useful for sending form data, including files, to a server via an HTTP request..

Setting Up a Next.js Project

First, let’s set up a basic Next.js project. If you haven’t already, install the Next.js framework:

npx create-next-app@latest my-formdata-app

cd my-formdata-app

Client-Side Handling of FormData

In this section, we’ll create a form that includes text inputs and a file upload input. We’ll then use FormData to handle the form submission.

Code :

// components/UploadForm.js

import { useState } from 'react'

const UploadForm = () => {
  const [formData, setFormData] = useState({
    name: '',
    file: null,
  })

  const handleChange = (e) => {
    const { name, value, files } = e.target
    if (name === 'file') {
      setFormData({ ...formData, file: files[0] })
    } else {
      setFormData({ ...formData, [name]: value })
    }
  }

  const handleSubmit = async (e) => {
    e.preventDefault()
    const data = new FormData()
    data.append('name', formData.name)
    data.append('file', formData.file)

    const response = await fetch('/api/upload', {
      method: 'POST',
      body: data,
    })

    if (response.ok) {
      alert('File uploaded successfully')
    } else {
      alert('File upload failed')
    }
  }

  return (
    <form onSubmit={handleSubmit}>
      <input
        type="text"
        name="name"
        value={formData.name}
        onChange={handleChange}
        required
      />
      <input type="file" name="file" onChange={handleChange} required />
      <button type="submit">Upload</button>
    </form>
  )
}

export default UploadForm

2.Using the Form Component in a Page

Create a new page, pages/index.js, and include the UploadForm component:

Code :

// components/UploadForm.js
// pages/index.js
import UploadForm from '../components/UploadForm'
import UploadForm from '../components/UploadForm'

const Home = () => (
  <div>
    <h1>Upload Your File</h1>
    <UploadForm />
  </div>
)

export default Home

Server-Side Handling of FormData

Next.js allows us to handle API routes easily. We’ll create an API endpoint to handle the form submission.

1.Creating the API Route Create a new API route, pages/api/upload.js:

Create a new page, pages/index.js, and include the UploadForm component:

Code :

// pages/api/upload.js
import formidable from 'formidable'
import formidable from 'formidable'
import fs from 'fs'

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

export default function handler(req, res) {
  if (req.method === 'POST') {
    const form = new formidable.IncomingForm()
    form.uploadDir = './public/uploads' // Ensure this directory exists
    form.keepExtensions = true

    form.parse(req, (err, fields, files) => {
      if (err) {
        res.status(500).json({ error: 'File upload error' })
        return
      }

      const oldPath = files.file.filepath
      const newPath = `./public/uploads/${files.file.originalFilename}`
      fs.rename(oldPath, newPath, (err) => {
        if (err) {
          res.status(500).json({ error: 'File rename error' })
          return
        }
        res.status(200).json({ message: 'File uploaded successfully' })
      })
    })
  } else {
    res.status(405).json({ error: 'Method not allowed' })
  }
}

Conclusion

Handling FormData in Next.js is straightforward with the app router. By following this guide, you’ve learned how to create a form with file uploads on the client side and process those uploads on the server side. This approach ensures a seamless experience for users uploading files to your Next.js application. Consider integrating additional features like validation, progress tracking, and error handling for more advanced handling. Happy coding!

More articles

Popular UI Patterns and Graphic Styles in Modern Web Design

Popular UI patterns and graphic styles in modern web design emphasize minimalism, responsiveness, and user-centric elements, incorporating trends like dark mode, bold typography, and microinteractions.

Read more

The Power of Typography in Web Design: Making Text Easy to Read

Good typography can make a big difference in how users interact with your site. Let's explore why typography matters and how to use it effectively.

Read more

Ready to transform your ideas into reality?

Let's discuss how we can help you achieve your business goals with innovative software solutions

Get in touch