Snippet: Mailchimp Newsletter Subscribe

Snippet

Back

Mailchimp Newsletter Subscribe

logo for Mailchimp

Send form submission data to Mailchimp list

A very basic example of a newsletter signup form, which takes the submitted email address and creates a new member in our Mailchimp list.

// /api/subscribe.js
export default async (req, res) => {
    const { email } = req.body
    const url = `https://usX.api.mailchimp.com/3.0/lists/${process.env.MAILCHIMP_LIST_ID}/members`

    try {
        const response = await fetch(url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `apikey ${process.env.MAILCHIMP_API_KEY}`
            },
            body: JSON.stringify({
                email_address: email,
                status: 'subscribed'
            })
        });
        const data = await response.json()
        res.status(200).json({ message: 'Successfully subscribed', data })
    } catch (error) {
        res.status(400).json({ message: 'Failed to subscribe', error })
    }
}
// in your component 
const handleSubmit = async (e) => {
  e.preventDefault()
  const email = e.target.elements.email.value
  try {
      const response = await fetch('/api/subscribe', {
          method: 'POST',
          headers: {
              'Content-Type': 'application/json'
          },
          body: JSON.stringify({ email }),
      })
      const data = await response.json()
      // handle the response data
  } catch (error) {
      // handle the error
  }
}

return (
  <form onSubmit={handleSubmit}>
      <input type="email" name="email" placeholder="Enter your email" required />
      <button type="submit">Subscribe</button>
  </form>
)

In the 2nd code block for the component, we are using the fetch function to make a POST request to the `/api/subscribe.js` route with a JSON payload containing the user's email address. The email address is extracted from the form data using the e.target.elements.email.value method, where `e` is the event object passed to the handleSubmit function.

In the handleSubmit function, we are also handling the response by calling response.json() and handling the data returned. Of course this is very basic, so you will need to tweak it to your liking.

Loading...