Next.js Examples
Next.js integration examples using API routes and Server Components. Learn how to integrate Metigan into your Next.js applications securely.
API Route Example
app/api/send-email/route.tsTypeScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import { NextRequest, NextResponse } from 'next/server';
import Metigan from 'metigan';
const metigan = new Metigan({
apiKey: process.env.METIGAN_API_KEY!
});
export async function POST(request: NextRequest) {
try {
const body = await request.json();
const { to, subject, content } = body;
const result = await metigan.email.sendEmail({
from: 'noreply@example.com',
recipients: [to],
subject,
content
});
if ('success' in result && result.success) {
return NextResponse.json({
success: true,
trackingId: result.successfulEmails[0]?.trackingId
});
} else {
return NextResponse.json(
{ success: false, error: result.message || 'Failed to send email' },
{ status: 400 }
);
}
} catch (error) {
return NextResponse.json(
{ success: false, error: error instanceof Error ? error.message : 'Unknown error' },
{ status: 500 }
);
}
}Server Component Example
app/emails/page.tsxTypeScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import Metigan from 'metigan';
const metigan = new Metigan({
apiKey: process.env.METIGAN_API_KEY!
});
export default async function EmailsPage() {
// Server Components can directly use Metigan
const contacts = await metigan.contacts.list({ limit: 10 });
return (
<div>
<h1>Contacts</h1>
<ul>
{contacts.items.map(contact => (
<li key={contact.id}>{contact.email}</li>
))}
</ul>
</div>
);
}Environment Variables
Store your API key in .env.localand access it via process.env.METIGAN_API_KEY