How to implement form submission with Next.js
Next.js is a widely used and open-source framework in web development. It's a go-to framework in terms of both server-side and client-side rendering. Next provides configurations for React applications and adds its own features on top of the structure as well.
Note: Next.js offers vast features and can be learned through building applications here.
A great way to learn about a new Javascript technology is to try and implement a form using static techniques e.g., HTML, and CSS, and then applying some kind of validation on it.
Moving on with this intent, we will be building an easy-to-understand form in Next.js and allow submission and validation checks on the submitted input. Let's dive right in!
Setting up a Next.js project
Before we move on to the code, let's learn how to get our project up and running first. The procedure for a Next.js project is quite similar to that of React in terms of both commands and syntax.
First, we're going to open up a directory and initialize our project in the same directory.
npx create-next-app .
Then, the terminal will prompt us with a few settings that we'll say either "Yes" or "No" to, according to our project scope and requirements.
The project structure should be similar to the given structure.
We can now run our application using this command.
npm run dev
Form submission through Next.js
To make a form, we can use React or Next.js elements and then make a few validation functions. The validation will be taken care of through our application's backend i.e. the server.
Next.js Form
Here's how we render a form in Next.js.
"use client";import React, { useState } from 'react';import './globals.css';export default function Home() {const [myEmail, setMyEmail] = useState('');const [myPassword, setMyPassword] = useState('');const [confirmMyPassword, setMyConfirmPassword] = useState('');return (<div className="flex flex-col text-white items-center justify-center h-screen bg-gray-900"><p className = 'pb-14 font-bold text-2xl'>Instructions for the form</p><p>1. Make sure your password contains atleast 6 characters</p><p className = 'pb-24'>2. Your email must contain the domain "educative.io"</p><form className="rounded-lg w-full max-w-md p-8 bg-gray-700"><label htmlFor="email" className="text-gray-200">Add your Email here</label><inputtype="text"placeholder="e.g. i@educative.io"requiredvalue={myEmail}onChange={(e) => setMyEmail(e.target.value)}name="email"className="w-full px-4 py-2 mb-4 bg-gray-900 rounded-md border border-gray-400 text-gray-100 focus:outline-none focus:border-gray-500"/><label htmlFor="password" className="text-gray-200">Add your Password here</label><inputtype="password"placeholder="e.g. *********"requiredvalue={myPassword}onChange={(e) => setMyPassword(e.target.value)}name="password"className="w-full px-4 py-2 mb-4 bg-gray-900 border border-gray-400 rounded-md text-gray-100 focus:outline-none focus:border-gray-500"/><label htmlFor="confirmPassword" className="text-gray-200">Confirm Password here</label><inputtype="password"placeholder="e.g. *********"requiredvalue={confirmMyPassword}onChange={(e) => setMyConfirmPassword(e.target.value)}name="confirmPassword"className="w-full px-4 py-2 mb-4 bg-gray-900 border border-gray-400 rounded-md text-gray-100 focus:outline-none focus:border-gray-500"/><buttontype="submit"onClick={handleMySubmission}className="w-full py-2 px-4 bg-gray-800 rounded-md text-gray-100 hover:bg-gray-600 focus:outline-none">Submit Form in Next.js!</button></form></div>);}
Now let's assume we have the following requirements:
Each
emailshould contain "educative.io".The
passwordlength should be greater than 6.The contents of the
passwordandconfirmPasswordfields should match.
handleMySubmission(e) in form
To implement submission so that the backend is triggered, let's code up a handleMySubmission function.
const handleMySubmission = (e) => {e.preventDefault();fetch('http://localhost:4000/api/submitForm', {method: 'POST',body: JSON.stringify({ email: myEmail, password: myPassword, confirmPassword: confirmMyPassword }),headers: {'Content-Type': 'application/json',},}).then((response) => {if (response.status === 200) {setMyEmail("");setMyPassword("");setMyConfirmPassword("");}return response.json();}).then((data) => {alert(JSON.stringify(data.message));}).catch((error) => {console.error(error);alert('An error occurred. Please try again.');});};
Server set up for the backend
A safer and widely accepted way of validation of forms is from a backend being set up for our application. Therefore, we will not be handling these checks in our handleMySubmission method.
A server is pretty easy to set up with Express, so let's quickly do that before bringing our application together.
const express = require('express');var cors = require('cors')const app = express();const bodyParser = require('body-parser');const port = 4000;app.use(cors());app.use(bodyParser.json());app.post('/api/submitForm', (req, res) => {const { email, password, confirmPassword } = req.body;if (password.length < 6) {res.status(400).json({ message: 'Your password length must be greater than 6' });return;}if (password !== confirmPassword) {res.status(400).json({ message: 'Password and confirm password fields do not match' });return;}if (!email.includes('@educative.io')) {res.status(400).json({ message: 'Email domain does not match' });return;}res.status(200).json({ message: 'Form submitted successfully' });});app.listen(port, () => {console.log(`API server is running on port ${port}`);});
Full stack application
All that we've learned in this answer can help us make a complete and ready-to-run full-stack Next.js and Express project from scratch. We can now submit a form and see its validation in action.
Let's join the pieces together and run our application!