I’m trying to test out a contact form in Next.js, it logs the data entered, but not able to send the data to the API, keep getting error
"POST http://localhost:3000/app/(pages)/api/contact/route.tsx 404 (Not Found)"
trying to find out what’s wrong
[the directory setup] (image)(https://phpout.com/wp-content/uploads/2024/01/kz5ch.png)'use client'
import { useState, FormEvent } from "react"
import React from "react"
export const ContactForm = () => {
const [name, setName] = useState('')
const [email, setEmail] = useState('')
const [message, setMessage] = useState('')
const onSubmit = async (e: FormEvent) => {
e.preventDefault()
try {
const res = await fetch('/app/(pages)/api/contact/route.tsx',{
method: 'POST',
body: JSON.stringify({
name, email, message
}),
headers: {
'content-type': 'application/json'
}
})
if (res.ok) {
// Handle success
console.log('Submission successful');
} else {
// Handle errors
console.error('Submission failed');
}
} catch (err:any) {
console.error('Err', err)
}
}
return (
<main>
<form
className="contact-form"
onSubmit={onSubmit}>
<input
value={name}
onChange={e => setName(e.target.value)}
name="name"
type="text"
placeholder="NAME"
required/>
<input
value={email}
onChange={e => setEmail(e.target.value)}
name="email"
type="text"
placeholder="EMAIL"
required/>
<textarea
value={message}
onChange={e => setMessage(e.target.value)}
name="message"
id=""
placeholder="MESSAGE"
/>
<button type="submit">SEND</button>
</form>
</main>
)
}
The contact-form.tsx code
import type { NextApiRequest, NextApiResponse } from "next";
export default function handler(req: NextApiRequest, res: NextApiResponse){
console.log('Data', req.body)
res.status(200).json({name: "John Doe"})
}
the app/api/contact/route.tsx file code currently
attempted fixes
- changed pages directory from "(pages)" to "pages"
- copied path directly and copy pasted into fetch
2
Answers
Seems you’re using NextJs 14. Convert the file name from app/api/contact/route.tsx into app/api/contact/route.ts
Replace the current code of route.ts with this
See the documentation for more https://nextjs.org/docs/app/api-reference/functions/next-response
When you submit the button and fetch the data never use an extension like ‘route.tsx’
On the client side
On the Api Route Side
When you make a directory like ‘app/pages/api/contact/route.ts’
it will detect file ‘/pages/api/contact’
The Folder Directory is here
I hope it will help you. good luck!