unsent
unsent.dev
Guides

Nuxt

How to send emails with Unsent in Nuxt

Introduction

This guide shows how to send emails using Unsent in a Nuxt application using Server Routes.

Install dependencies

npm install @unsent/sdk
pnpm add @unsent/sdk
yarn add @unsent/sdk
bun add @unsent/sdk

Configure API Key

Add your Unsent API key to your .env file.

.env
UNSENT_API_KEY=un_...

And configure it in nuxt.config.ts.

nuxt.config.ts
export default defineNuxtConfig({
  runtimeConfig: {
    unsentApiKey: process.env.UNSENT_API_KEY,
  },
});

Create Server Route

Create a server route in server/api/send.post.ts.

server/api/send.post.ts
import { Unsent } from '@unsent/sdk';

const config = useRuntimeConfig();
const unsent = new Unsent(config.unsentApiKey);

export default defineEventHandler(async (event) => {
  const body = await readBody(event);
  const { email } = body;

  const { data, error } = await unsent.emails.send({
    from: 'Acme <onboarding@unsent.dev>',
    to: [email],
    subject: 'Hello world',
    html: '<strong>It works!</strong>',
  });

  if (error) {
    throw createError({
      statusCode: 500,
      statusMessage: error.message,
    });
  }

  return data;
});

Call API

Call the API from your Vue component.

app.vue
<script setup>
async function sendEmail() {
  await $fetch('/api/send', {
    method: 'POST',
    body: { email: 'delivered@unsent.dev' }
  });
  alert('Email sent!');
}
</script>

<template>
  <button @click="sendEmail">Send Email</button>
</template>