Next.js 14 Contact Form with Server Actions, Nodemailer, React Hook Form, Zod, Tailwind CSS, reCAPTCHA, and TypeScript
This is a template for a contact form with Next.js. It uses a custom server to send the email and validate the form. It also uses reCAPTCHA to prevent spam. Handlebars is used to create the email template.
For pages
router visit https://github.com/ozcancelik/nextjs-mail-form repository.
https://nextjs-14-mail-form-ozcancelik.vercel.app/
- Next.js with Server Actions for handling form submissions
- Custom server: You can run with different port. It's useful for same server with other apps.
- Nodemailer
- React Hook Form
- Zod
- reCAPTCHA with react-google-recaptcha It uses the invisible reCAPTCHA v2. More info about reCAPTCHA: https://developers.google.com/recaptcha/docs/display
- Email templating with Handlebars. https://github.com/yads/nodemailer-express-handlebars
- TypeScript
- CSS with Tailwind CSS
- Icons with React Icons
### Prerequisites
- Clone the repository and install the dependencies.
- Create a
.env
file or change the name of.env.example
to.env
and fill the variables.
SERVER_PORT=
CONTACT_FORM_SEND_EMAIL=
CONTACT_FORM_RECEIVE_EMAIL=
CONTACT_FORM_PASS=
CONTACT_FORM_HOST=
NEXT_PUBLIC_RECAPTCHA_SITE_KEY=
RECAPTCHA_SECRET_KEY=
npm install
# or
yarn
### Run the development server:
npm run dev
# or
yarn dev
### Build the app
npm run build
# or
yarn build
### Run the production server:
npm run start
# or
yarn start
- You can change the server port in
.env
file. If empty, it will use the default port 3000. - If you have problems with Nodemailer, you can try to change the port or other settings. You can find more info in the Nodemailer documentation. More info: https://nodemailer.com/smtp/
- Gmail requires you to enable "Less secure app access" in your account settings. More info: https://nodemailer.com/usage/using-gmail/
- For the reCAPTCHA to work, you need to add the domain to the reCAPTCHA admin panel.
Tested with Node.js v18.12.1.
Server Actions is a new feature introduced in Next.js 13 that allows you to handle form submissions on the server-side without the need for a separate API route or server.
You can find the server actions in the @/app/actions
file. The sendContactForm
function is used to send the email.