Setup a Newsletter with Next.js and Mailchimp
--
Having a Newsletter subscription on your blog can be beneficial. It provides a way for you to keep your readers up to date with your content, drive traffic to your blog, and It is a great way to communicate with your readers.
In this tutorial, you will learn how to set up a Newsletter on your Next Js blog with Mailchimp.
Why Mailchimp?
MailChimp is a popular online marketing tool that you can use to manage your email list when you start getting subscribers. They have a free version for people with 2000 contacts or less. It’s good enough for people beginning their newsletter journey.
Get started with Next Js
Next Js makes building APIs so simple. All you need is to create a pages/api
folder, Next Js will map any file inside to /api/*
and it becomes an endpoint instead of a page.
Mailchimp Setup
To get started, create an account with Mailchimp. When a user subscribes to your newsletter, the email address is added to your Audience
. Mailchimp gives you API Keys
that you can use in other apps to access your account.
To connect to the API we will need three environmental variables from Mailchimp;
Setup environmental variables for development and production
It’s best practice to store environmental variables in.env
files, do not push your environmental variables to your remote branch. remember to add the.env.local
file to .gitignore.
Local Setup
Create a .env.local
file
MAILCHIMP_API_KEY=”your-mailchimp-api-key”MAILCHIMP_AUDIENCE_ID=”your-mailchimp-audience-id”MAILCHIMP_API_SERVER=”your-api-server-prefix”
Production Setup
I have my blog app deployed on Netlify. To add these variables to Netlify,
go to Site settings > Build & deploy > Environment > Edit Variables.
Add environment variables in Vercel.
Create Server-side API request
Create pages/api/subscribe.js
Install axios, import it in subscribe.js
. I love how simple it is to use axios to make API requests. I’m using axios to make a post request to the Mailchimp marketing API.
Create an async function that takes a request
and response
as parameters.
the If block adds a validation check so that the email request body isn’t an empty string.
Use process.env
to grab the env variables, update the Mailchimp URL with the env variable.
Create a data object containing the email address and a subscribed status. An option
object that tells the content type and sets the authorisation header to your api_key
.
The code in the try block makes a post request to the URL endpoint using axois with the data and options passed in as parameters.
if the email input field is empty or invalid, a 400(bad request) status error response is returned, else a 201(created) status response is returned. In case of any other errors, a 500 server error is returned.
Note: It’s important to be sure of the arguments Mailchimp API takes. while working on this, I added a `first name` input field to the data object and the API kept returning a 500 server error. I studied what the Mailchimp API takes in as arguments and that solved the server response problem for me. That is after trying to get a form field for `first name` and `email` to work. The moral of this part is to be sure of the data structure the API will need before creating the frontend UI for it.
To add additional params, see the full list of available params.
Create Newsletter form component
Now we have an API that takes an email and submits it to Mailchimp API. Let’s create the client-side UI where user can input their email to subscribe. I used styled-components
to style the form component.
create a Subscribe.js
file in src/components
folder.
I created three state variables;
- email state
- a loading state
- an error state
When a user clicks the Subscribe button
, Subscribe function is called. the state is set to Loading while the request is being made to the API.
based on the response we get, the state is either set to Success for a successful submission or Error and returns an error message.
While waiting for the server response, the state is set to Loading, the button is set to disabled
. I did this to prevent users from clicking the button again and as a way to let them know their request is processing.
{
state === "Error" && (
<ErrorState className="error-state">{errorMsg}</ErrorState>
);
}
{
state === "Success" && (
<SuccessState>Awesome, you've been subscribed!</SuccessState>
);
}
This displays the API response to the client. If no errors, the email is added to your Mailchimp audience dashboard.
Fix API route not found in a Next.js App Production Environment.
Be sure to test your subscription form in the production environment. While my subscribe form worked well locally, I discovered it wasn’t working in production. It returned a 404 not found
error. The reason was that API Routes can’t be used with next export. After removing next export
from my build script, It worked as expected.
View the final result on agirl.codes.
Conclusion
To view the complete code, checkout out my blog source code on GitHub.
I hope this article was helpful. If you have any questions or comments, do share.
The Complete Guide to Building React Forms with useState Hook
For a quick overview of how to build forms with react hook, [check this article.