Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

238
Visualizações
How to send email using sendrid with next js?

i have an issue with my contact form. It send email but the user input is undefined. When i log the data on the console it is returned correctly but on vs code terminale all the information is undefined.

console log in browser dev tool return the below

{firstName: 'test ', email: 'test@test.com', phone: '382552', message: 'test '}
email: "test@test.com"
firstName: "test "
message: "test "
phone: "382552"
[[Prototype]]: Object

the console log in vs code terminal

{
  to: 'info@test.com',
  from: 'info@test.com',
  subject: 'New message from undefined undefined',
  text: '\n' +
    '  FirstName: undefined\r\n' +
    '\n' +
    '  Email: undefined\r\n' +
    '\n' +
    '  phone:undefined\n' +
    '  Message: undefined\r\n' +
    '\n',
  html: '\n' +
    '  FirstName: undefined<br />\n' +
    '  Email: undefined<br />\n' +
    '  phone:undefined\n' +
    '  Message: undefined<br />\n',

The message should be containing the details log on the browser console.

api/contact

import cookie from "cookie";

const mail = require("@sendgrid/mail");

mail.setApiKey(process.env.NEXT_PUBLIC_SENDGRID_API_KEY);

// eslint-disable-next-line import/no-anonymous-default-export
export default async (req, res) => {
  res.setHeader(
    "Set-Cookie",
    cookie.serialize("token", req.body.token, {
      httpOnly: true,
      secure: process.env.NODE_ENV !== "development",
      expires: new Date(0),
      maxAge: 60 * 60,
      sameSite: "strict",
      path: "/",
    })
  );

  const body = JSON.parse(JSON.stringify(req.body));

  const message = `
  FirstName: ${body.firstName}\r\n
  Email: ${body.email}\r\n
  phone:${body.phone}
  Message: ${body.message}\r\n
`;

  const data = {
    to: "info@test.com",
    from: "info@test.com",
    subject: `New message from ${body.firstName} ${body.phone}`,
    text: message,
    html: message.replace(/\r\n/g, "<br />"),
  };
  try {
    await mail.send(data);
    console.log(data);
    res.status(200).json({ status: "OK" });
  } catch (error) {
    console.log("server error", error);
    if (error.response) {
      console.log(error.response.body);
    }
    res.status(400).json({ status: "ERROR", message: error.message });
  }
};
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

  1. Are you using body-parser (npm package)?
  2. Not sure why you use JSON.stringify(JSON.parse(req.body)) seems like a waste of computer resources? This strategy is sometimes useful as the non-fastest way to deep clone an object (however structured clone: which can easily be used like const clone = structuredClone(original); is easier to use and probably faster).
  3. what do you mean by browser's dev tool I assume that means on the client side when you make the request? So we're pretty sure the payload of the request looks good. Might be better to make sure by checking the payload in the browser's actual request (like in Chrome check Network tab of dev tools and filter to look only at Fetch/XHR then check for the specific request and it's Request Headers/Payload).
  4. Next verify that the body is being received as expected and is properly being parsed by body-parser the defacto node-js library for parsing the body. You should be able to console.log(req.body) and have that show everything.
  5. If that looks good and SendGrid is still not working as expected then check on the documentation.
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda