ArkarDev

Sending Newsletters Made Easy with Next.js 13 Server Actions

May 24, 2023Arkar Kaung Myat
NextjsTypescriptReact

Check out this blog post on using Next.js 13 server actions and Mailgun! Don't wait, start building your own newsletter today and share your passion with the world!

I updated my Next.js 13 app since the early release and had to use some tips and tricks to make it work, but now that it's stable, it's been amazing. With the stable release of Next.js 13, the new server actions feature is now available. This powerful feature allows developers to handle server-side logic directly in their Next.js app without the need for a separate backend.

I have been planning to build a newsletter for my blog and I am also excited to explore the new server actions feature in Next.js. This new server actions feature is amazing because it has the potential to revolutionize the way we think about server-side logic in web development. By utilizing this combination of Next.js and a third-party service like Mailgun, I can just focus on creating high-quality content for their subscribers while also providing a seamless user experience.

Since my website is using Sanity, I will store all subscriber information in a separate database and use API routes to handle controller logic. I can also utilize third-party services such as Mailgun to send emails to my subscribers.

Checkout my website's repo here

# Server actions in Next.js

Server Actions are an alpha feature in Next.js, built on top of React Actions . They allow for server-side data mutations, reduced client-side JavaScript, and progressively enhanced forms. To use them, you can enable them under a flag in the Next.js config.

module.exports = {
  experimental: {
    serverActions: true,
  },
};

One big advantage of using server actions in Next.js is that you can run server code directly in your frontend app. In Next.js, you can use the api or, now, you can use them directly in server components with server actions.

export async function add_user(
  email: string,
  name: string
): Promise<QueryResultRow<User> | null> {
  try {
    const result = await queryDb<User>(
      `INSERT INTO mailing_list (name, email) VALUES ('${name}', ${email}') RETURNING *`
    );
		return result
  } catch (e) {
    return null;
  }
}

You can also invoke server actions using a button with the type="submit" attribute on an <form> element. This will trigger the server action when the form is submitted.

For example:

<form action={addUserAction} method="POST">
  <input type="text" name="name" placeholder="Name" />
  <input type="email" name="email" placeholder="Email" />
  <button type="submit">Subscribe</button>
</form>

The action attribute is set to the URL of the server action API route. When the form is submitted by clicking the "Subscribe" button, the add_user server action will be called with the values of the name and email input fields as parameters.

# Triggering with useTransition

You can also use react’s useTransition hook to that lets you update the state without blocking the UI. The useTransition hook is an excellent tool for improving user experience. By providing a loading state while the server action is processing, users are reassured that the app is still working and not frozen. This can greatly improve user engagement and satisfaction.

...
const [isSubmitting, startTransition] = useTransition({
  timeoutMs: 3000,
});

async function handleSubmit(event) {
  event.preventDefault();
  startTransition(() => {
    add_user(email, name);
  });
}

return (
  <form onSubmit={handleSubmit}>
    <input type="text" name="name" placeholder="Name" />
    <input type="email" name="email" placeholder="Email" />
    <button type="submit" disabled={isSubmitting}>
      {isSubmitting ? 'Submitting...': 'Subscribe'}
    </button>
  </form>
);
...

# Mailgun with Next.js

Mailgun is a popular email service that allows developers to send transactional and marketing emails through an API. To use Mailgun in a Next.js app, you can create an API route that handles the email-sending logic. In addition to using the Mailgun API, you can also use SMTP to send emails from your Next.js app. To use SMTP, you can use a package like nodemailer to handle the email-sending logic.

To use Mailgun, you need to set up your own website address and confirm it with Mailgun. After confirming your website address, you can start sending emails using it. Mailgun provides detailed instructions on how to add the necessary DNS records for popular DNS providers such as GoDaddy, Cloudflare, and Namecheap. After adding the DNS records, you can verify your domain in the Mailgun dashboard.

Mailgun supports email templates, which can simplify the process of sending emails with consistent formatting. Email templates are pre-designed emails that you can customize with your own content to match your brand and style. Using email templates can save you time and effort by eliminating the need to create each email from scratch.

To use email templates with Mailgun, you can create a template on the Mailgun website or through their API. Once created, you can use the Mailgun API to send emails using that template. You can also use variables in your email templates to personalize the content of your emails. For instance, you might use a variable to insert the subscriber's name into the email greeting.

Mailgun also offers batch sending, which can come in handy when you need to send a large number of emails. With batch sending, you can send up to 1,000 emails at a time by listing multiple recipients in a single API call. To use batch sending with Mailgun, you can call the messages().send() method with a list of recipient email addresses.

const API_KEY = process.env.MAILGUN_API_KEY as string;
const DOMAIN = process.env.MAILGUN_DOMAIN as string;

const mg = mailgun({ apiKey: API_KEY, domain: DOMAIN });

const recipients = ['user1@example.com', 'user2@example.com', 'user3@example.com'];

const data = {
  from: 'Excited User <me@samples.mailgun.org>',
  to: recipients.join(','),
  subject: 'Hello',
  text: 'Testing some Mailgun awesomeness!'
};

mg.messages().send(data, (error, body) => {
  console.log(body);
});

And there you have it! With Next.js 13's server actions and Mailgun, you can create a newsletter that is both easy to manage and a joy for your readers to receive. So what are you waiting for? Start building your own newsletter today and share your passion with the world! Don't forget to subscribe to my newsletter for more tips and tricks on web development.