Platform
Docs
Solutions
ContactLog In

Start Routing Notifications Today!

Courier is a notification service that centralizes all of your templates and messaging channels in one place which increases visibility and reduces engineering time.

Sign-up

Invoys Header
ENGINEERINGCOURIER

How to Send Invoice and Add Payment Reminder in Next.js with Courier API

Fazza Razaq Amiarso

January 27, 2023

Background

A lot of open-source invoice management apps are built with Laravel. As a Javascript developer, I wanted to build the “React Solution” for devs that are familiar with React and Javascript.

A problem I found when building with services in Node.js is that there is no built-in mailer. So, I had to find a 3rd party service to do that for me. In this article, I will be integrating Courier to send emails for this project https://github.com/fazzaamiarso/invoys.

Pre-requisites

As this article isn't your typical follow-along (more like "please sit tight and see how I do it"), it's not mandatory to be familiar with all technologies used. However, familiarity with Typescript and Next.js will be beneficial for quicker understanding.

Technologies in this blog:

  • Typescript: type-safety and auto-completion are the best, right?
  • Next.js: a production-ready framework to build a full-stack app, even for beginners.
  • Prisma: a great ORM to work with databases. We use Prisma because of its type-safety and auto-completion, providing great developer experience with typescript added.
  • Trpc: enable us to easily build end-to-end type-safety between our Next.js client and server.
  • Courier API: a great service/platform to handle our notifications, such as email, SMS, and much more.

You can find the full source code here for reference.

Goals

Before building the features, let's define our goals.

  1. Send invoice link to client's email.
  2. Send a reminder a day before an invoice's due date.
  3. Cancel an invoice due date reminder when the invoice is already paid.
  4. Handling network errors.

Part 1: Setup Courier Platform

Let's head over to the Courier Dashboard. By default, it's in a production environment. Since I want to test things out, I'm going to change to the test environment by clicking the dropdown in the top-right corner.

We can copy all templates later to production or vice-versa.

Now, I will create a brand for my email notifications.

go to brand

I'm just going to add a logo (beware that the logo width is fixed to 140px) on the header and social links on the footer. The designer UI is pretty straightforward, so here is the final result.

brand template

Don't forget to publish the changes.

Part 2: Send Invoice to Email

Currently, the send email button on the UI is doing nothing.

I'm going to create a courier.ts file in src/lib/ to keep all Courier-related code. Also, I will use courier node.js client library which already abstracted all Courier API endpoints to functions.

Before I build the functionality, let's create the email notification design within Courier's Designer and set up the Gmail provider.

On the email designer page, we will see that the created brand is already integrated. After that, let's design the template accordingly with the needed data. Here is the final result.

email template finalaction button

Notice the value with {} that becomes green, it means it's a variable that can be inserted dynamically. I also set the 'See Invoice' button (or action) with a variable.

Before I can use the template, I need to create a test event by clicking the preview tab. Then, it will show a prompt to name the event and set data in JSON format. That data field is what will populate the value of the green {} variables (the data can be set from code also). Since it's a test event, I will fill it with arbitrary values.

Next, I will publish the template so I can use it. Then, go to send tab. It will show the necessary code to send the email programmatically and the data will be populated with the previous test event that I created.

code snippet

Backend

I will copy the test AUTH_TOKEN to the .env file and copy the snippet to src/lib/courier.ts.

1
const authToken = process.env.COURIER_AUTH_TOKEN;
2
3
// email to receive all sent notifications in DEVELOPMENT mode
4
const testEmail = process.env.COURIER_TEST_EMAIL;
5
6
const INVOICE_TEMPLATE_ID = <TEMPLATE_ID>;
7
8
const courierClient = CourierClient({
9
authorizationToken: authToken,
10
});

Create a sendInvoice function that will be responsible for sending an email. To send an email from the code, I use the courierClient.send() function.

1
// src/lib/courier.ts
2
3
export const sendInvoice = async ({
4
customerName,
5
invoiceNumber,
6
invoiceViewUrl,
7
emailTo,
8
productName,
9
dueDate,
10
}: SendInvoice) => {
11
12
const recipientEmail = process.env.NODE_ENV === "production" ? emailTo : testEmail;
13
14
const { requestId } = await courierClient.send({
15
message: {
16
to: {
17
email: recipientEmail,
18
},
19
template: INVOICE_TEMPLATE_ID,
20
// Data for courier template designer
21
data: {
22
customerName,
23
invoiceNumber,
24
invoiceViewUrl,
25
productName,
26
dueDate,
27
},
28
},
29
});
30
return requestId
31
};

Define types for the sendInvoice function.

1
// src/lib/courier.ts
2
3
interface SendInvoice {
4
productName: string;
5
dueDate: string;
6
customerName: string;
7
invoiceNumber: string;
8
invoiceViewUrl: string;
9
emailTo: string;
10
}

Now that I can send the email, I will call it in the sendEmail trpc endpoint that resides in src/server/trpc/router/invoice.ts.

Just remember that trpc endpoint is a Next.js API route. In this case, sendEmail will be the same as calling the /api/trpc/sendEmail route with fetch under the hood. For more explanation https://trpc.io/docs/quickstart.

1
// src/server/trpc/router/invoice.ts
2
import { sendInvoice } from '@lib/courier';
3
import { dayjs } from '@lib/dayjs';
4
5
// .....SOMEWHERE BELOW
6
sendEmail: protectedProcedure
7
.input(
8
z.object({
9
customerName: z.string(),
10
invoiceNumber: z.string(),
11
invoiceViewUrl: z.string(),
12
emailTo: z.string(),
13
invoiceId: z.string(),
14
productName: z.string(),
15
dueDate: z.date(),
16
})
17
)
18
.mutation(async ({ input }) => {
19
const invoiceData = {
20
...input,
21
dueDate: dayjs(input.dueDate).format('D MMMM YYYY'),
22
};
23
24
await sendInvoice(invoiceData);
25
}),

For those who are unfamiliar with trpc, what I did is the same as handling a POST request. Let's break it down.

  1. Trpc way of defining request input from client by validating with Zod. Here I define all data that are needed for the sendInvoice function.
1
.input(
2
z.object({
3
customerName: z.string(),
4
invoiceNumber: z.string(),
5
invoiceViewUrl: z.string(),
6
emailTo: z.string(),
7
invoiceId: z.string(),
8
productName: z.string(),
9
dueDate: z.date(),
10
})
11
)
  1. Define a POST request handler (mutation).
1
// input from before
2
.mutation(async ({ input }) => {
3
const invoiceData = {
4
...input,
5
// format a date to string with a defined format.
6
dueDate: dayjs(input.dueDate).format('D MMMM YYYY'), // ex.'2 January 2023'
7
};
8
9
// send the email
10
await sendInvoice(invoiceData);
11
}),

Frontend

Now, I can start to add the functionality to the send email button. I'm going to use the trpc.useMutation() function which is a thin wrapper of tanstack-query'suseMutation`.

Let's add the mutation function. On successful response, I want to send a success toast on UI.

1
//src/pages/invoices/[invoiceId]/index.tsx
2
import toast from 'react-hot-toast';
3
4
const InvoiceDetail: NextPage = () => {
5
// calling the `sendEmail` trpc endpoint with tanstack-query.
6
const sendEmailMutation = trpc.invoice.sendEmail.useMutation({
7
onSuccess() {
8
toast.success('Email sent!');
9
}
10
});
11
}

I can just use the function as an inline handler, but I want to create a new handler for the button.

1
//src/pages/invoices/[invoiceId]/index.tsx
2
3
// still inside the InvoiceDetail component
4
const sendInvoiceEmail = () => {
5
const hostUrl = window.location.origin;
6
7
// prevent a user from spamming when the API call is not done.
8
if (sendEmailMutation.isLoading) return;
9
10
// send input data to `sendEmail` trpc endpoint
11
sendEmailMutation.mutate({
12
customerName: invoiceDetail.customer.name,
13
invoiceNumber: `#${invoiceDetail.invoiceNumber}`,
14
invoiceViewUrl: `${hostUrl}/invoices/${invoiceDetail.id}/preview`,
15
emailTo: invoiceDetail.customer.email,
16
invoiceId: invoiceDetail.id,
17
dueDate: invoiceDetail.dueDate,
18
productName: invoiceDetail.name,
19
});
20
};

Now I can attach the handler to the send email button.

1
//src/pages/invoices/[invoiceId]/index.tsx
2
3
<Button
4
variant="primary"
5
onClick={sendInvoiceEmail}
6
isLoading={sendEmailMutation.isLoading}>
7
Send to Email
8
</Button>

Here's the working UI.

working ui

Part 3: Send Payment Reminder

To schedule a reminder that will be sent a day before an invoice's due date, I'm going to use Courier's Automation API.

First, let's design the email template in Courier designer. As I already go through the process before, here is the final result.

payment reminder template

Before adding the function, define the types for the parameter and refactor the types.

1
// src/lib/courier
2
3
interface CourierBaseData {
4
customerName: string;
5
invoiceNumber: string;
6
invoiceViewUrl: string;
7
emailTo: string;
8
}
9
10
interface SendInvoice extends CourierBaseData {
11
productName: string;
12
dueDate: string;
13
}
14
15
interface ScheduleReminder extends CourierBaseData {
16
scheduledDate: Date;
17
invoiceId: string;
18
}

Now, I add the scheduleReminder function to src/lib/courier

1
//src/pages/invoices/[invoiceId]/index.tsx
2
3
// check if the development environment is production
4
const __IS_PROD__ = process.env.NODE_ENV === 'production';
5
6
const PAYMENT_REMINDER_TEMPLATE_ID = '<TEMPLATE_ID>';
7
8
export const scheduleReminder = async ({
9
scheduledDate,
10
emailTo,
11
invoiceViewUrl,
12
invoiceId,
13
customerName,
14
invoiceNumber,
15
}: ScheduleReminder) => {
16
17
// delay until a day before due date in production, else 20 seconds after sent for development
18
const delayUntilDate = __IS_PROD__
19
? scheduledDate
20
: new Date(Date.now() + SECOND_TO_MS * 20);
21
22
const recipientEmail = __IS_PROD__ ? emailTo : testEmail;
23
24
// define the automation steps programmatically
25
const { runId } = await courierClient.automations.invokeAdHocAutomation({
26
automation: {
27
steps: [
28
// 1. Set delay for the next steps until given date in ISO string
29
{ action: 'delay', until: delayUntilDate.toISOString() },
30
31
// 2. Send the email notification. Equivalent to `courierClient.send()`
32
{
33
action: 'send',
34
message: {
35
to: { email: recipientEmail },
36
template: PAYMENT_REMINDER_TEMPLATE_ID,
37
data: {
38
invoiceViewUrl,
39
customerName,
40
invoiceNumber,
41
},
42
},
43
},
44
],
45
},
46
});
47
48
return runId;
49
};

To send the reminder, I will call scheduleReminder after a successful sendInvoice attempt. Let's modify the sendEmail trpc endpoint.

1
// src/server/trpc/router/invoice.ts
2
3
sendEmail: protectedProcedure
4
.input(..) // omitted for brevity
5
.mutation(async ({ input }) => {
6
// multiplier for converting day to milliseconds.
7
const DAY_TO_MS = 1000 * 60 * 60 * 24;
8
9
// get a day before the due date
10
const scheduledDate = new Date(input.dueDate.getTime() - DAY_TO_MS * 1);
11
12
const invoiceData = {..}; //omitted for brevity
13
14
await sendInvoice(invoiceData);
15
16
//after the invoice is sent, schedule the reminder
17
await scheduleReminder({
18
...invoiceData,
19
scheduledDate,
20
});
21
}

Now if I try to send an invoice by email, I should get a reminder 20 seconds later since I'm in the development environment.

with payment reminder

Part 4: Cancel a reminder

Finally, all the features are ready. However, I got a problem, what if a client had paid before the scheduled date for payment reminder? Currently, the reminder email will still be sent. That's not a great user experience and potentially a confused client. Thankfully, Courier has an automation cancellation feature.

Let's add cancelAutomationWorkflow function that can cancel any automation workflow in src/lib/courier.ts.

1
export const cancelAutomationWorkflow = async ({
2
cancelation_token,
3
}: {
4
cancelation_token: string;
5
}) => {
6
const { runId } = await courierClient.automations.invokeAdHocAutomation({
7
automation: {
8
// define a cancel action, that sends a cancelation_token
9
steps: [{ action: 'cancel', cancelation_token }],
10
},
11
});
12
13
return runId;
14
};

What is a cancelation_token? It's a unique token that can be set to an automation workflow, so it's cancelable by sending a cancel action with a matching cancelation_token.

Add cancelation_token to scheduleReminder, I use the invoice's Id as a token.

1
// src/lib/courier.ts
2
3
export const scheduleReminder = async(..) => {
4
// ...omitted for brevity
5
6
const { runId } = await courierClient.automations.invokeAdHocAutomation({
7
automation: {
8
// add cancelation token here
9
cancelation_token: `${invoiceId}-reminder`,
10
steps: [
11
{ action: 'delay', until: delayUntilDate.toISOString() },
12
13
// ... omitted for brevity

I will call cancelAutomationWorkflow when an invoice's status is updated to PAID in the updateStatus trpc endpoint.

1
// src/server/trpc/router/invoice.ts
2
3
updateStatus: protectedProcedure
4
.input(..) // omitted for brevity
5
.mutation(async ({ ctx, input }) => {
6
const { invoiceId, status } = input;
7
8
// update an invoice's status in database
9
const updatedInvoice = await ctx.prisma.invoice.update({
10
where: { id: invoiceId },
11
data: { status },
12
});
13
14
// cancel payment reminder automation workflow if the status is paid.
15
if (updatedInvoice.status === 'PAID') {
16
17
//call the cancel workflow to cancel the payment reminder for matching cancelation_token.
18
await cancelAutomationWorkflow({
19
cancelation_token: `${invoiceId}-reminder`,
20
});
21
}
22
23
return updatedStatus;
24
}),

Here is the working UI.

cancel log

Part 5: Error Handling

An important note when doing network requests is there are possibilities of failed requests/errors. I want to handle the error by throwing it to the client, so it can be reflected in UI.

On error, Courier API throws an error with CourierHttpClientError type by default. I will also have all functions' return value in src/lib/courier.ts consistent with the below format.

1
// On Success
2
type SuccessResponse = { data: any, error: null }
3
4
// On Error
5
type ErrorResponse = { data: any, error: string }

Now, I can handle errors by adding a try-catch block to all functions in src/lib/courier.ts.

1
try {
2
// ..function code
3
4
// modified return example
5
return { data: runId, error: null };
6
7
} catch (error) {
8
// make sure it's an error from Courier
9
if (error instanceof CourierHttpClientError) {
10
return { data: error.data, error: error.message };
11
} else {
12
return { data: null, error: "Something went wrong!" };
13
}
14
}

Let's see a handling example on the sendEmail trpc endpoint.

1
// src/server/trpc/router/invoice.ts
2
3
const { error: sendError } = await sendInvoice(..);
4
if (sendError) throw new TRPCClientError(sendError);
5
6
const { error: scheduleError } = await scheduleReminder(..);
7
if (scheduleError) throw new TRPCClientError(scheduleError);

Part 6: Go To Production

Now that all templates are ready, I will copy all assets in the test environment to production. Here is an example.

copy assets to production

Conclusion

Finally, all the features are integrated with Courier. We've gone through a workflow of integrating Courier API to a Next.js application. Although it's in Next.js and trpc, the workflow will be pretty much the same with any other technology. I hope now you can integrate Courier into your application by yourself.

Get started now: https://app.courier.com/signup

About the Author

I'm Fazza Razaq Amiarso, a full-stack web developer from Indonesia. I'm also an Open Source enthusiast. I love to share my knowledge and learning on my blog. I occasionally help other developers on FrontendMentor in my free time.

Connect with me on LinkedIn.

🔗 Courier Docs

🔗 Contribute to Invoys

🔗 Invoys Motivation

Start Routing Notifications Today!

Courier is a notification service that centralizes all of your templates and messaging channels in one place which increases visibility and reduces engineering time.

Sign-up

More from Engineering

courier-ios-thumbnail
PRODUCT NEWSENGINEERING

Simplifying notifications with the Courier iOS SDK

Push notifications are a valuable tool for keeping users informed and increasing their engagement with your app. You can use push notifications to alert users about promotions, new content, or any other important updates. While push notifications are a powerful tool, setting up push notifications in iOS can be a daunting task that requires a significant amount of effort and time. Fortunately, the Courier iOS Mobile Notifications Software Development Kit (SDK) simplifies this process.

Mike Miller

Mike Miller

March 23, 2023

Courier Android SDK thumbnail
PRODUCT NEWSENGINEERING

Building Android push notifications with Firebase and Courier’s SDK

Push notifications have become an essential part of modern mobile apps, allowing you to keep your users engaged and informed. However, implementing push for different platforms can be a complex and time-consuming task, requiring developers to set up and handle token management, testing, and other logistical details.

Mike Miller

Mike Miller

March 21, 2023

Build your first notification in minutes

Send up to 10,000 notifications every month, for free.

Get started for free

Email & push notification

Build your first notification in minutes

Send up to 10,000 notifications every month, for free.

Get started for free

Email & push notification

Platform

Users

Content

Channels

Sending

Workflows

Preferences

Inbox

Workspaces

Observability

API Status

Changelog

© 2024 Courier. All rights reserved.