2024-12-05 Web Development
Building a Contact submission form in Next.js 15 and Notion
By O. Wolfson
This article demonstrates how to implement a secure, functional contact form that integrates client-side validation, Google reCAPTCHA, and a server-side connection to Notion for storing submissions.
Overview
This contact form workflow consists of:
- A React-based user interface for capturing inputs.
- Validation on both the client and server using Zod.
- Server-side handling of submissions with Next.js server actions.
- Integration with the Notion API to store form data.
Contact Form Implementation
The form is a React component rendered on the client. It includes fields for the sender's email, name, message type, subject, and message content. Google reCAPTCHA is used to prevent spam.
Code Example
Server-Side Processing
Server actions in Next.js allow direct server-side processing without a dedicated API route. This example uses sendContactMessage
to validate input and store it in Notion.
Validation and API Request
Integration with Notion
Notion serves as the storage backend. Each form submission creates a new page in a specified Notion database.
Setup
-
Create a Notion integration and retrieve the API key.
-
Add the database ID and API key to
.env.local
:NOTION_API_KEY=your-api-key NEXT_PUBLIC_NOTION_DATABASE_ID=your-database-id
-
Ensure database properties align with the payload structure defined in
sendContactMessage
.
How It Works
- The user completes the form and reCAPTCHA.
- The client validates the input and submits it to the server action.
- The server validates the data again and sends it to Notion via its API.
- On success, the user is redirected or notified.
Advantages of This Approach
- Simplified Server Logic: Server actions eliminate the need for traditional API endpoints.
- Enhanced Security: Sensitive operations and environment variables remain on the server.
- Validation on Both Ends: Zod ensures data integrity on both the client and server.
- Spam Prevention: Google reCAPTCHA integration reduces automated submissions.
Conclusion
Using Next.js 15's App Router and server actions, you can implement a contact form with clear separation of concerns, robust validation, and secure handling of user data. This approach is adaptable for other backends and use cases while maintaining simplicity and reliability.