Integration Guide
Guide for integrating AI Store with external services and platforms.
Analytics Integration
Google Analytics
// Add to layout.tsx
import { GoogleAnalytics } from '@next/third-parties/google';
export default function Layout({ children }) {
return (
<>
{children}
<GoogleAnalytics gaId="G-XXXXXXXXXX" />
</>
);
}
Custom Analytics
import { advancedAnalytics } from '@/lib/analytics-advanced';
// Track page view
advancedAnalytics.pageView('/page');
// Track event
advancedAnalytics.trackEvent({
name: 'button_click',
category: 'interaction',
});
Error Tracking
Sentry Integration
import * as Sentry from '@sentry/nextjs';
Sentry.init({
dsn: process.env.NEXT_PUBLIC_SENTRY_DSN,
environment: process.env.NODE_ENV,
});
Custom Error Tracking
import { errorLogger } from '@/lib/error-logger';
errorLogger.log(error, 'high', {
context: 'component',
userId: 'user-123',
});
Authentication
NextAuth.js
// app/api/auth/[...nextauth]/route.ts
import NextAuth from 'next-auth';
import GoogleProvider from 'next-auth/providers/google';
export const authOptions = {
providers: [
GoogleProvider({
clientId: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
}),
],
};
export default NextAuth(authOptions);
Custom Authentication
// lib/auth.ts
export async function authenticate(credentials: Credentials) {
// Your authentication logic
const user = await verifyCredentials(credentials);
return user;
}
Database Integration
Prisma
// lib/prisma.ts
import { PrismaClient } from '@prisma/client';
const prisma = new PrismaClient();
export default prisma;
Usage
// app/api/users/route.ts
import prisma from '@/lib/prisma';
export async function GET() {
const users = await prisma.user.findMany();
return NextResponse.json(users);
}
Payment Integration
Stripe
import Stripe from 'stripe';
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY);
export async function POST(request: Request) {
const session = await stripe.checkout.sessions.create({
payment_method_types: ['card'],
line_items: [/* items */],
mode: 'payment',
success_url: `${process.env.NEXT_PUBLIC_SITE_URL}/success`,
cancel_url: `${process.env.NEXT_PUBLIC_SITE_URL}/cancel`,
});
return NextResponse.json({ sessionId: session.id });
}
Email Integration
SendGrid
import sgMail from '@sendgrid/mail';
sgMail.setApiKey(process.env.SENDGRID_API_KEY);
export async function sendEmail(to: string, subject: string, html: string) {
await sgMail.send({
to,
from: process.env.SENDGRID_FROM_EMAIL,
subject,
html,
});
}
Resend
import { Resend } from 'resend';
const resend = new Resend(process.env.RESEND_API_KEY);
export async function sendEmail(to: string, subject: string, html: string) {
await resend.emails.send({
from: process.env.RESEND_FROM_EMAIL,
to,
subject,
html,
});
}
Storage Integration
AWS S3
import { S3Client, PutObjectCommand } from '@aws-sdk/client-s3';
const s3 = new S3Client({
region: process.env.AWS_REGION,
credentials: {
accessKeyId: process.env.AWS_ACCESS_KEY_ID,
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
},
});
export async function uploadFile(file: Buffer, key: string) {
await s3.send(new PutObjectCommand({
Bucket: process.env.AWS_BUCKET_NAME,
Key: key,
Body: file,
}));
}
Cloudinary
import { v2 as cloudinary } from 'cloudinary';
cloudinary.config({
cloud_name: process.env.CLOUDINARY_CLOUD_NAME,
api_key: process.env.CLOUDINARY_API_KEY,
api_secret: process.env.CLOUDINARY_API_SECRET,
});
export async function uploadImage(file: Buffer) {
const result = await cloudinary.uploader.upload(file, {
folder: 'ai-store',
});
return result.secure_url;
}
API Integration
REST API
// lib/api-client.ts
export class APIClient {
private baseURL: string;
constructor(baseURL: string) {
this.baseURL = baseURL;
}
async get<T>(endpoint: string): Promise<T> {
const response = await fetch(`${this.baseURL}${endpoint}`);
if (!response.ok) throw new Error('API Error');
return response.json();
}
async post<T>(endpoint: string, data: any): Promise<T> {
const response = await fetch(`${this.baseURL}${endpoint}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data),
});
if (!response.ok) throw new Error('API Error');
return response.json();
}
}
GraphQL
import { GraphQLClient } from 'graphql-request';
const client = new GraphQLClient(process.env.GRAPHQL_ENDPOINT, {
headers: {
authorization: `Bearer ${token}`,
},
});
export async function query<T>(query: string, variables?: any): Promise<T> {
return client.request<T>(query, variables);
}
Webhook Integration
Receiving Webhooks
// app/api/webhooks/route.ts
import { NextRequest, NextResponse } from 'next/server';
import crypto from 'crypto';
export async function POST(request: NextRequest) {
const body = await request.text();
const signature = request.headers.get('x-signature');
// Verify signature
const expectedSignature = crypto
.createHmac('sha256', process.env.WEBHOOK_SECRET)
.update(body)
.digest('hex');
if (signature !== expectedSignature) {
return NextResponse.json({ error: 'Invalid signature' }, { status: 401 });
}
const data = JSON.parse(body);
// Process webhook
return NextResponse.json({ received: true });
}
Sending Webhooks
export async function sendWebhook(url: string, payload: any) {
const signature = crypto
.createHmac('sha256', process.env.WEBHOOK_SECRET)
.update(JSON.stringify(payload))
.digest('hex');
await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Signature': signature,
},
body: JSON.stringify(payload),
});
}
Third-Party Services
Integration Checklist
- [ ] API keys configured
- [ ] Environment variables set
- [ ] Error handling implemented
- [ ] Rate limiting considered
- [ ] Security measures in place
- [ ] Testing completed
- [ ] Documentation updated
Best Practices
1. Secure API Keys
// Never expose in client code
const apiKey = process.env.SERVER_ONLY_API_KEY; // ✅
const apiKey = process.env.NEXT_PUBLIC_API_KEY; // ⚠️ Only if necessary
2. Error Handling
try {
const result = await externalAPI.call();
return result;
} catch (error) {
errorLogger.log(error, 'high');
throw new Error('Integration failed');
}
3. Rate Limiting
import { rateLimiter } from '@/lib/rate-limit';
const result = rateLimiter.check('api-key', 100, 60000);
if (!result.allowed) {
throw new Error('Rate limit exceeded');
}
4. Caching
import { advancedCache } from '@/lib/advanced-cache';
const data = await advancedCache.get('key', async () => {
return await externalAPI.fetch();
}, { ttl: 60000 });