Sending custom response in netlify-forms submission

Hello team,
Is there any way to send a custom response apart from the netlify-form submission returning a generic thank-you html

exports.handler = async function (event, context, callback) {
  try {
    const parsedBody = JSON.parse(event.body);

    console.log(parsedBody);

    const { countrycode = null, mobilenumber = null } = parsedBody.payload.data;

    console.log(countrycode, mobilenumber, "<== numbers");

    if (!countrycode || !mobilenumber) {
      return callback("Please make sure to enter a valid mobile number");
    }

    const generatedOtp = generateOTP();

    const response = await client.messages.create({
      from: BOT_NUMBER,
      to: `${countrycode}${mobilenumber}`,
      body: `Your verification code is ${generatedOtp}`,
    });

    console.log(
      CryptoJS.AES.encrypt(
        CryptoJS.enc.Utf8.parse(generatedOtp),
        REACT_APP_CRYPTO_JS_SECRET_KEY,
      ).toString(),
    );

    if (!response.errorCode && !response.errorMessage) {
      console.log(" response success");
      return callback(null, {
        statusCode: 200,
        body: "just a test",
        statusText: "test for status text",
      });
    }

    return callback("Something went wrong, Please try again later");
  } catch (error) {
    return callback(error);
  }
};

i want to return a string as shown in the example above, but at the end it always returns the thank you html. Can anyone please help me with this?

Hey @deepp

You can set a custom thank you (or success) page while using Netlify Forms as outlined in the Success messages documentation.

Otherwise, you could look at the Submit HTML forms with AJAX documentation (on the same page as the link above) and display a message on screen.

The example code you have used in a function which would not use Netlify Forms, rather you would need to handle the form submission by sending it via email or submitting it to another data store (e.g. database.)

So is there any way i can generate the redirect url on the netlify-function?

something like this:- /verify?code=fsskjfsufuisfsfsjkfskjhsdh and then send in the response or tell netlify to redirect to this url with the params intact?

Can you explain why you are wanting to redirect? Why with a verification code? What is it you are trying to accomplish?

i have made a form containing phone details, i want to check whether the phone is verified or not through otp, so is the integration of twillio comes in,

on submit , i am triggering the form-function provided by netlify, that business logic generates and send otp to given number

I don’t want to store this otp in any datastore as you suggested above

i want to send data (json) in response as shown above

So i am trying to redirect to custom page with params as mentioned above

I hope you get what i am trying to do here

Better (IMHO) that you use the AJAX method as I previously linked to, for form submission. The function can then return a status code, and success/error response (as JSON if you wish) which is then displayed to the user. You can do this on same page the form is submitted on without redirecting.

Should you wish to have a redirect come from the function on success and/or error, use the Location header to specify where to redirect to.

That’s the solution i used, but does nothing good, i get the generic success page html in response.data

just to confirm this, i am trying this in a react app

here is the form onSubmit handler


const handleVerify = async (e) => {
    e.preventDefault();
    try {
      setSendingOtp(true);
      const response = await axios.post(
        "/",
        encode({
          "form-name": "contact",
          countrycode: values.countrycode,
          mobilenumber: values.mobilenumber,
        }),
        {
          headers: {
            "Content-Type": "application/x-www-form-urlencoded",
            Accept: "application/json",
          },
        },
      );

      if (response.status === 200) {
        sessionStorage.setItem("code", response.data);
        restart(getTwoMinutesTime());
        setVerificationTextField(true);
        setShowOtpTimer(true);
        setOtp({ code: "", error: "", success: false });
        setSendingOtp(false);
        toast.success(
          "Verification code has been sent to your given mobile number",
        );
      }
    } catch (error) {
      setSendingOtp(false);
      toast.error(error?.response?.data || error.message);
    }
  };

the static html inside index.html:


<form name="contact" netlify netlify-honeypot="bot-field" hidden>
        <input type="text" name="countrycode" />
        <input type="text" name="mobilenumber" />
    </form>

and the form used inside the jsx component:


<form name="contact" netlify netlify-honeypot="bot-field">
                      <Grid
                        container
                        rowSpacing={1}
                        columnSpacing={{ xs: 1, sm: 2, md: 3 }}
                        paddingLeft="28px"
                        className="Country-Code-grid"
                      >
                        <Grid item md={4} className="Country-Code-item">
                          <Item>
                            <Box
                              sx={{
                                "& .MuiTextField-root": {},
                              }}
                              noValidate
                              autoComplete="off"
                            >
                              <div className="Country-Code-field">
                                <Box
                                  className="form_field"
                                  sx={{ minWidth: 120 }}
                                >
                                  <FormControl fullWidth>
                                    <InputLabel
                                      variant="standard"
                                      htmlFor="uncontrolled-native"
                                      className="form_control"
                                    >
                                      Country Code*
                                    </InputLabel>
                                    <NativeSelect
                                      inputProps={{
                                        name: "countrycode",
                                        id: "uncontrolled-native",
                                      }}
                                      name="countrycode"
                                      value={values?.countrycode}
                                      onChange={handleChange}
                                    >
                                      {CountryCodeData &&
                                        CountryCodeData.length > 0 &&
                                        CountryCodeData.map((country, key) => (
                                          <option
                                            key={key}
                                            value={country.dial_code}
                                          >
                                            {country.name} ({country.dial_code})
                                          </option>
                                        ))}
                                    </NativeSelect>
                                  </FormControl>
                                </Box>
                              </div>
                              {errors.countrycode && touched.countrycode && (
                                <div className="error-message">
                                  {errors.countrycode}
                                </div>
                              )}
                            </Box>
                          </Item>
                        </Grid>
                        <Grid item md={4}>
                          <Item>
                            <Box
                              sx={{
                                "& .MuiTextField-root": {},
                              }}
                              noValidate
                              autoComplete="off"
                            >
                              <div className="form_field">
                                <TextField
                                  id="control-field"
                                  label="Mobile Number"
                                  type="text"
                                  InputLabelProps={{
                                    shrink: true,
                                  }}
                                  className="form_control"
                                  name="mobilenumber"
                                  value={values?.mobilenumber}
                                  onChange={handleChange}
                                  variant="filled"
                                />
                              </div>
                              {errors.mobilenumber && touched.mobilenumber && (
                                <div className="error-message">
                                  {errors.mobilenumber}
                                </div>
                              )}
                            </Box>
                          </Item>
                        </Grid>
                          <Grid style={{ marginTop: "2rem" }} item md={4}>
                            <LoadingButton
                              loading={sendingOtp}
                              className="form-btn form-processd-btn"
                              variant="contained"
                              onClick={handleVerify}
                            >
                              Send OTP
                            </LoadingButton>
                          </Grid>
                        
                      </Grid>
                    </form>

this always return html string of success page

If you are using a function to handle form submission, you do not add the netlify or netlify-honeypot attributes to the form.

handleVerify is submitting the form using Netlify Forms, not using the function in your original post. If you want to submit using the function, you need to POST to /.netlify/functions/<your-function-name>, not simply /.

So how come this all works good in localhoast (with netlify dev) but breaks in while deploying?

Also can you please explain me a bit more on this??

I can’t explain why it appears to work with Netlify CLI and not when deployed to Netlify unless I can see the code for myself.

One possibility is Netlify forms don’t work locally, only when deployed to Netlify

Explain more about what specifically?

using this solution, it returns me with an 403 forbidden error , any luck you know why this is happening?

this is the request config i am using, is there anything wrong here?

 const response = await axios.post(
        "/.netlify/functions/submission-created",
        {
          "form-name": "contact",
          countrycode: values.countrycode,
          mobilenumber: values.mobilenumber,
        },
        {
          headers: {
            "Content-Type": "application/x-www-form-urlencoded",
            Accept: "application/json",
          },
        },
      );

You can’t post to the submission-created function. The submission-created function is triggered automatically. If you are wanting to post to a function, start by changing the name.

Hiya, sorry you are having trouble getting your forms to work.

This Support Guide is the first port of call to debug any forms issues. Please start here and work through these resources!

We also recommend trying to search the forums or look at topics tagged Netlify forms if you haven’t already - it’s likely your question was already asked by someone else!

If you are still having problems, please provide your form name as it exists in the UI as well as a link to your live form.

@coelmay , thanks for your time in providing the help, we have finally achieved what we wanted to do

Thanks for your time and help

1 Like