| name | integrate-external-api |
| description | Use when integrating third-party APIs (e.g. SMTP emails, SMS notification gateways, payment checkout gates, or OCR parsers). |
Integrate Third-Party APIs Playbook
Follow these best practices to connect external software services securely and reliably:
-
Environment Config:
- Save credentials (keys, tokens, client IDs) inside
.env and .env.example.
- Never commit raw API keys to GitHub.
- Reference them using
process.env.API_KEY_NAME.
-
Abstract Service Layer (Mockable):
- Create a service utility class inside
src/lib/services/ (e.g. mail.ts, sms.ts).
- Write a mock variant that handles local development offline without firing active API calls:
export async function sendEmail(to: string, subject: string, body: string) {
if (process.env.NODE_ENV === "development") {
console.log(`[MOCK EMAIL SENT TO ${to}]: ${subject} - ${body}`);
return { success: true, messageID: "mock-12345" };
}
}
- This ensures your app runs perfectly offline during local developer trials without hitting quota limits or throwing network timeout exceptions.
-
Client-side Fetch Handlers:
- Trigger the service operations from server-side Route Handlers (
src/app/api/...), and fetch them using standard fetch functions from client components.
- Show loading/disabled states on forms during active fetch executions.