Contact Us Form using Next.js
Last Updated :
23 Jul, 2025
Creating a Contact Us form in Next.js involves setting up a form component, handling form submissions, and potentially integrating with a backend service or API to send the form data. In this article, we will create a Contact Us Form with NextJS.
Output Preview: Let’s have a look at what our final project will look like:
Building a Contact Us Form with Next.jsPrerequisites:
Approach
To create contact us form using Next.js, we will use:
- The Home component to renders the contact form.
- The ContactForm component handles user input, submission, and displays success or error messages.
- Accepts POST requests with contact form data.
- Uses Mongoose to connect to MongoDB and store the contact information.
- Returns JSON responses indicating success or failure, including error messages for validation failures.
- The database setup uses MongoDB with Mongoose for defining a schema and interacting with the database.
Steps to Build a Contact Us Form with NextJS
Step 1: Set up NextJS project using the command
npx create-next-app@latest
What is your project named? > contact-us
Would you like to use TypeScript with this project? > No
Would you like to use ESLint with this project? > Yes
Would you like to use Tailwind CSS with this project? > Yes
Would you like to use 'src/'directory with this project? > No
Use App Router (recommended)? > Yes
Would you like to customize the default import alias? > No
Step 2: Navigate to the project folder using the below command.
cd contact-us
Step 3: Install the mongoose package using the command.
npm i mongoose
Project Structure:
Project Structure of Contact Us Form with Next.jsThe updated dependencies in the package.json file are:
"dependencies": {
"mongoose": "^8.5.1",
"next": "14.2.4",
"react": "^18",
"react-dom": "^18"
}
Step 4: Set up MongoDB for database.
- Simply search for MongoDB Atlas and create a free account.
- Create a cluster.
- Create a New Project as ContactForm .
- Build a Database using the Free version.
- Create a username and password.
- Add the IP Address as 0.0.0.0/0 so that we can access this database from anywhere.
- Click on Connect and select MongoDB for VS Code.
- Copy the connection string and replace <password> with your password.
Create a file as .env in the project folder . Paste the connection string you have just copied and put it equal to MONGODB_URL variable with contact_db appended at the end of the connection string as given below.
MONGODB_URL=mongodb+srv://<username>:<password>@cluster0.jxzdjvc.mongodb.net/contact_db
Explanation:
- Create a folder “components” and add a new file in it namely ContactForm.jsx.
- Create a folder “api” under the folder app . Create a sub-folder contact and add a new file in it namely route.js.
- Create a folder “lib” under the folder app and add a new file in it namely mongodb.js.
- Create a folder “models” under the folder app and add a new file in it namely contact.js.
- Modify files of the folder app i.e. global.css, layout.js, and page.jsx.
Example: Below is an example of building a Contact Us Form with NextJS.
CSS
/* Filename - globals.css */
@tailwind base;
@tailwind components;
@tailwind utilities;
form>div {
@apply flex flex-col gap-2;
}
input,
textarea {
@apply shadow-md px-6 py-2 border border-slate-300;
}
JavaScript
// Filename - page.jsx
import ContactForm from "@/components/ContactForm";
export default function Home() {
return (
<div className="p-4 max-w-3xl mx-auto">
<h1 className="text-3xl font-bold">
Contact Us
</h1>
<p>Please fill in the form below</p>
<ContactForm />
</div>
);
}
JavaScript
// Filename - layout.js
import { Inter } from "next/font/google";
import "./globals.css";
const inter = Inter({ subsets: ["latin"] });
export const metadata = {
title: "Contact Us",
description: "Generated by create next app",
};
export default function RootLayout({ children }) {
return (
<html lang="en">
<body className={inter.className}>
{children}
</body>
</html>
);
}
JavaScript
// Filename - components/ContaxtForm.jsx
"use client";
import { useState } from "react";
export default function ContactForm() {
const [fullname, setFullname] = useState("");
const [email, setEmail] = useState("");
const [message, setMessage] = useState("");
const [error, setError] = useState(null);
const [success, setSuccess] = useState(false);
const handleSubmit = async (e) => {
e.preventDefault();
console.log("Full name: ", fullname);
console.log("Email: ", email);
console.log("Message: ", message);
const res = await fetch("api/contact", {
method: "POST",
headers: {
"Content-type": "application/json",
},
body: JSON.stringify({
fullname,
email,
message,
}),
});
const { msg, success } = await res.json();
setError(msg);
setSuccess(success);
if (success) {
setFullname("");
setEmail("");
setMessage("");
}
};
return (
<>
<form
onSubmit={handleSubmit}
className="py-4 mt-4 border-t flex flex-col gap-5"
>
<div>
<label htmlFor="fullname">Full Name</label>
<input
onChange={(e) => setFullname(e.target.value)}
value={fullname}
type="text"
id="fullname"
placeholder="John Doe"
/>
</div>
<div>
<label htmlFor="email">Email</label>
<input
onChange={(e) => setEmail(e.target.value)}
value={email}
type="text"
id="email"
placeholder="[email protected]"
/>
</div>
<div>
<label htmlFor="message">Your Message</label>
<textarea
onChange={(e) => setMessage(e.target.value)}
value={message}
className="h-32"
id="message"
placeholder="Type your message here..."
></textarea>
</div>
<button className="bg-green-700 p-3 text-white font-bold"
type="submit">
Send
</button>
</form>
<div className="bg-slate-100 flex flex-col">
{error && (
<div
className={`${success ? "text-green-800" : "text-red-600"
} px-5 py-2`}
>
{error}
</div>
)}
</div>
</>
);
}
JavaScript
// Filename - api/contact/route.js
import connectDB from "@/app/lib/mongodb";
import Contact from "@/app/models/contact";
import { NextResponse } from "next/server";
import mongoose from "mongoose";
export async function POST(req) {
const { fullname, email, message } = await req.json();
try {
await connectDB();
await Contact.create({ fullname, email, message });
return NextResponse.json({
msg: ["Message sent successfully"],
success: true,
});
} catch (error) {
if (error instanceof mongoose.Error.ValidationError) {
let errorList = [];
for (let e in error.errors) {
errorList.push(error.errors[e].message);
}
console.log(errorList);
return NextResponse.json({ msg: errorList });
} else {
return NextResponse.json({
msg: ["Unable to send message."]
});
}
}
}
JavaScript
// Filename - lib/mongodb.js
import mongoose from "mongoose";
const connectDB = async () => {
try {
if (mongoose.connection.readyState === 0) {
await mongoose.connect(process.env.MONGODB_URL);
console.log("db connected");
}
} catch (error) {
console.log(error);
}
};
export default connectDB;
JavaScript
// Filename - modals/contact.js
import mongoose, { Schema } from "mongoose";
const contactSchema = new Schema({
fullname: {
type: String,
required: [true, "Name is required."],
trim: true,
minLength: [2, "Name must be larger than 2 characters"],
maxLength: [50, "Name must be lesser than 50 characters"],
},
email: {
type: String,
required: [true, "Email is required."],
match: [/^[\w.%+-]+@[\w.-]+\.[A-Za-z]{2,}$/i,
"Invalid email address"],
},
message: {
type: String,
required: [true, "Message is required."],
},
date: {
type: Date,
default: Date.now,
},
});
const Contact =
mongoose.models.Contact || mongoose.model("Contact",
contactSchema);
export default Contact;
Start your application using the following command.
npm run dev
Output : Open web-browser and type the following URL http://localhost:3000/
Building a Contact Us Form with NextJS
Similar Reads
React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
React Fundamentals
React IntroductionReactJS is a component-based JavaScript library used to build dynamic and interactive user interfaces. It simplifies the creation of single-page applications (SPAs) with a focus on performance and maintainability. Why Use React?Before React, web development faced issues like slow DOM updates and mes
7 min read
React Environment SetupTo run any React application, we need to first setup a ReactJS Development Environment. In this article, we will show you a step-by-step guide to installing and configuring a working React development environment.Pre-requisite:We must have Nodejs installed on our PC. So, the very first step will be
3 min read
React JS ReactDOMReactDOM is a core React package that provides methods to interact with the Document Object Model, or DOM. This package allows developers to access and modify the DOM. It is a package in React that provides DOM-specific methods that can be used at the top level of a web app to enable an efficient wa
3 min read
React JSXJSX stands for JavaScript XML, and it is a special syntax used in React to simplify building user interfaces. JSX allows you to write HTML-like code directly inside JavaScript, enabling you to create UI components more efficiently. Although JSX looks like regular HTML, itâs actually a syntax extensi
5 min read
ReactJS Rendering ElementsIn this article we will learn about rendering elements in ReactJS, updating the rendered elements and will also discuss about how efficiently the elements are rendered.What are React Elements?React elements are the smallest building blocks of a React application. They are different from DOM elements
3 min read
React ListsIn lists, React makes it easier to render multiple elements dynamically from arrays or objects, ensuring efficient and reusable code. Since nearly 85% of React Projects involve displaying data collections- like user profiles, product catalogs, or tasks- understanding how to work with lists.To render
4 min read
React FormsForms are an essential part of any application used for collecting user data, processing payments, or handling authentication. React Forms are the components used to collect and manage the user inputs. These components include the input elements like text field, check box, date input, dropdowns etc.
5 min read
ReactJS KeysA key serves as a unique identifier in React, helping to track which items in a list have changed, been updated, or removed. It is particularly useful when dynamically creating components or when users modify the list. In this article, we'll explore ReactJS keys, understand their importance, how the
5 min read
Components in React
React ComponentsIn React, React components are independent, reusable building blocks in a React application that define what gets displayed on the UI. They accept inputs called props and return React elements describing the UI.In this article, we will explore the basics of React components, props, state, and render
4 min read
ReactJS Functional ComponentsIn ReactJS, functional components are a core part of building user interfaces. They are simple, lightweight, and powerful tools for rendering UI and handling logic. Functional components can accept props as input and return JSX that describes what the component should render.Stateless (before hooks)
5 min read
React Class ComponentsClass components are ES6 classes that extend React.Component. They allow state management and lifecycle methods for complex UI logic.Used for stateful components before Hooks.Support lifecycle methods for mounting, updating, and unmounting.The render() method in React class components returns JSX el
4 min read
ReactJS Pure ComponentsReactJS Pure Components are similar to regular class components but with a key optimization. They skip re-renders when the props and state remain the same. While class components are still supported in React, it's generally recommended to use functional components with hooks in new code for better p
4 min read
ReactJS Container and Presentational Pattern in ComponentsIn this article we will categorise the react components in two types depending on the pattern in which they are written in application and will learn briefly about these two categories. We will also discuss about alternatives to this pattern. Presentational and Container ComponentsThe type of compon
2 min read
ReactJS PropTypesIn ReactJS PropTypes are the property that is mainly shared between the parent components to the child components. It is used to solve the type validation problem. Since in the latest version of the React 19, PropeTypes has been removed. What is ReactJS PropTypes?PropTypes is a tool in React that he
5 min read
React Lifecycle In React, the lifecycle refers to the various stages a component goes through. These stages allow developers to run specific code at key moments, such as when the component is created, updated, or removed. By understanding the React lifecycle, you can better manage resources, side effects, and perfo
7 min read
React Hooks
Routing in React
Advanced React Concepts
React Projects