Loading...
Loading...
Integrate Notify'n with your Next.js application using API Routes or Server Actions.
Add your API key to your environment variables:
NOTIFYN_API_KEY=ntfn_your_api_key_hereinterface SendEmailOptions {
from: string;
to: string | string[];
subject: string;
html?: string;
text?: string;
replyTo?: string;
}interface SendEmailResponse {
success: boolean;
id: string;
message: string;
}export async function sendEmail(options: SendEmailOptions): Promise<SendEmailResponse> {
const response = await fetch(`${API_URL}/api/v1/emails`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${process.env.NOTIFYN_API_KEY}`,
'Content-Type': 'application/json',
},
body: JSON.stringify(options),
}); if (!response.ok) {
const error = await response.json();
throw new Error(error.message || 'Failed to send email');
} return response.json();
}Create an API route to handle form submissions:
import { NextRequest, NextResponse } from 'next/server';
import { sendEmail } from '@/lib/notifyn';export async function POST(request: NextRequest) {
try {
const { name, email, message } = await request.json(); // Validate input
if (!name || !email || !message) {
return NextResponse.json(
{ error: 'All fields are required' },
{ status: 400 }
);
} // Send notification email
await sendEmail({
from: 'notifications@yourdomain.com',
to: 'you@yourdomain.com',
replyTo: email,
subject: `New Contact: ${name}`,
html: `
<h2>New Contact Form Submission</h2>
<p><strong>Name:</strong> ${name}</p>
<p><strong>Email:</strong> ${email}</p>
<p><strong>Message:</strong></p>
<p>${message}</p>
`,
}); return NextResponse.json({ success: true });
} catch (error) {
console.error('Contact form error:', error);
return NextResponse.json(
{ error: 'Failed to send message' },
{ status: 500 }
);
}
}Use Server Actions for a more streamlined approach:
'use server';import { sendEmail } from '@/lib/notifyn';interface ContactFormState {
success: boolean;
error?: string;
}export async function submitContactForm(
prevState: ContactFormState,
formData: FormData
): Promise<ContactFormState> {
const name = formData.get('name') as string;
const email = formData.get('email') as string;
const message = formData.get('message') as string; if (!name || !email || !message) {
return { success: false, error: 'All fields are required' };
} try {
await sendEmail({
from: 'notifications@yourdomain.com',
to: 'you@yourdomain.com',
replyTo: email,
subject: `Contact Form: ${name}`,
html: `
<h2>New message from ${name}</h2>
<p><strong>Email:</strong> ${email}</p>
<p>${message}</p>
`,
}); return { success: true };
} catch (error) {
console.error(error);
return { success: false, error: 'Failed to send message' };
}
}
import { useActionState } from 'react';
import { submitContactForm } from './actions';export default function ContactPage() {
const [state, formAction, isPending] = useActionState(submitContactForm, {
success: false,
}); return (
<form action={formAction} className="space-y-4 max-w-md">
{state.success && (
<div className="p-4 bg-green-100 text-green-800 rounded">
Message sent successfully!
</div>
)}
{state.error && (
<div className="p-4 bg-red-100 text-red-800 rounded">
{state.error}
</div>
)}
<div>
<label htmlFor="name">Name</label>
<input type="text" id="name" name="name" required />
</div>
<div>
<label htmlFor="email">Email</label>
<input type="email" id="email" name="email" required />
</div>
<div>
<label htmlFor="message">Message</label>
<textarea id="message" name="message" required />
</div>
<button type="submit" disabled={isPending}>
{isPending ? 'Sending...' : 'Send Message'}
</button>
</form>
);
}For projects using the Pages Router:
import type { NextApiRequest, NextApiResponse } from 'next';
import { sendEmail } from '@/lib/notifyn';export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
if (req.method !== 'POST') {
return res.status(405).json({ error: 'Method not allowed' });
} const { name, email, message } = req.body; if (!name || !email || !message) {
return res.status(400).json({ error: 'All fields required' });
} try {
await sendEmail({
from: 'notifications@yourdomain.com',
to: 'you@yourdomain.com',
replyTo: email,
subject: `Contact: ${name}`,
html: `<p>From: ${name} (${email})</p><p>${message}</p>`,
}); return res.status(200).json({ success: true });
} catch (error) {
console.error(error);
return res.status(500).json({ error: 'Failed to send' });
}
}