Next.js Integration
Send emails from Next.js with Transactional. Works with App Router and Server Actions.
Beginner
Prerequisites
- Node.js 18+ installed
- Next.js 14+ project
- Transactional account with API key
QUICK START
Get Started in Minutes
1
Install the SDK
Add the Transactional SDK to your project.
npm install @transactional/sdk2
Set up environment variables
Add your API key to .env.local
TRANSACTIONAL_API_KEY=your_api_key_here3
Create an email utility
Create a reusable email client in lib/email.ts
4
Send emails from Server Actions
Use the client in your server-side code
CODE EXAMPLES
Full Implementation
Email Client Setup
lib/email.ts
import { Transactional } from '@transactional/sdk';
export const emailClient = new Transactional({
apiKey: process.env.TRANSACTIONAL_API_KEY!,
});
Server Action
app/actions.ts
'use server';
import { emailClient } from '@/lib/email';
export async function sendWelcomeEmail(email: string, name: string) {
const { data, error } = await emailClient.emails.send({
from: 'hello@yourdomain.com',
to: email,
subject: `Welcome, ${name}!`,
html: `<h1>Welcome to our platform, ${name}!</h1>`,
});
if (error) {
throw new Error(error.message);
}
return { success: true, emailId: data.id };
}
Using in a Form
app/signup/page.tsx
import { sendWelcomeEmail } from '../actions';
export default function SignupPage() {
async function handleSubmit(formData: FormData) {
'use server';
const email = formData.get('email') as string;
const name = formData.get('name') as string;
await sendWelcomeEmail(email, name);
}
return (
<form action={handleSubmit}>
<input name="name" placeholder="Your name" required />
<input name="email" type="email" placeholder="Email" required />
<button type="submit">Sign Up</button>
</form>
);
}
Best Practices for Next.js
Use Server Actions
Always send emails from Server Actions or API routes, never from client components. This keeps your API key secure.
Handle Errors Gracefully
'use server';
import { emailClient } from '@/lib/email';
export async function sendEmail(to: string, subject: string, html: string) {
try {
const { data, error } = await emailClient.emails.send({
from: 'hello@yourdomain.com',
to,
subject,
html,
});
if (error) {
console.error('Email error:', error);
return { success: false, error: error.message };
}
return { success: true, id: data.id };
} catch (e) {
console.error('Unexpected error:', e);
return { success: false, error: 'Failed to send email' };
}
}Use React Email for Templates
Combine with React Email for beautiful, maintainable templates:
import { render } from '@react-email/render';
import WelcomeEmail from '@/emails/welcome';
const html = render(<WelcomeEmail name="John" />);
await emailClient.emails.send({
from: 'hello@yourdomain.com',
to: 'user@example.com',
subject: 'Welcome!',
html,
});