0

I deployed a website that made by Next.js in Netlify. I have a form in contact page and it's work well on development and production (by build command and then start). On the Netlify when the form is submitted, it's work perfectly and stored form data on MongoDB but return error code 502 and I have below error that is result of POST request for storing form data to local api endpoint: "Error [ERR_STREAM_WRITE_AFTER_END]: write after end"

https://a-blog-simple.netlify.app/contact

`

import { connectDatabase, insertDocument } from '../../lib/mongodb-utils';

async function handler(req, res) {
  if (req.method === 'POST') {
    const name = req.body.name;
    const email = req.body.email;
    const message = req.body.message;

    let client;

    if (
      !name ||
      name.trim() === '' ||
      !email.includes('@') ||
      !message ||
      message.trim() === ''
    ) {
      res.status(422).json({ message: 'Invalid input.' });
      return;
    }

    const newFormData = {
      date: new Date().toISOString(),
      name,
      email,
      message,
    };

    try {
      client = await connectDatabase();
    } catch (err) {
      res.status(500).json({ message: 'Connecting to the database failed.' });
      return;
    }

    try {
      await insertDocument(client, 'forms', newFormData);
      res
        .status(201)
        .json({ message: 'Successfully stored message.', data: newFormData });
    } catch (err) {
      res.status(500).json({ message: 'Storing message failed.' });
      client.close();
      return;
    }

    client.close();
  }
}

export default handler;

`

I've tried in different ways but I don't know what is caused this error code? This is only happened on Netlify

Hadi
  • 1
  • 3

0 Answers0