AI Integration via API: Next.js & Postgres
In this post, we'll walk through how to integrate AI features into your Next.js application using an external API and store the results in a Postgres database. This is a practical guide for developers looking to add smart features to their web apps.
1. Setting Up Next.js API Route
First, create an API route in your Next.js app to act as a proxy between your frontend and the AI service:
// pages/api/ai.ts
import type { NextApiRequest, NextApiResponse } from 'next';
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
const { prompt } = req.body;
const aiRes = await fetch('https://api.example.com/ai', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ prompt }),
});
const data = await aiRes.json();
res.status(200).json(data);
}
Security: Use Environment Variables
For better security, always store sensitive information like API URLs and keys in environment variables. In Next.js, you can use a .env.local
file:
# .env.local
AI_API_URL=https://api.example.com/ai
Then, update your API route to use process.env.AI_API_URL
:
// pages/api/ai.ts
import type { NextApiRequest, NextApiResponse } from 'next';
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
const { prompt } = req.body;
const aiRes = await fetch(process.env.AI_API_URL, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ prompt }),
});
const data = await aiRes.json();
res.status(200).json(data);
}
2. Calling the API from the Frontend
Use fetch
or axios
to call your API route from a React component:
async function getAIResponse(prompt) {
const res = await fetch('/api/ai', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ prompt }),
});
return res.json();
}
3. Storing Results in Postgres
Use an ORM like Prisma to save the AI response to your Postgres database:
// prisma/schema.prisma
model AIResult {
id Int @id @default(autoincrement())
prompt String
result String
createdAt DateTime @default(now())
}
// Example save function
import prisma from '@/lib/prisma';
async function saveResult(prompt, result) {
return await prisma.aIResult.create({
data: { prompt, result },
});
}
Conclusion
With this setup, you can easily add AI-powered features to your Next.js app and persist the results in Postgres for analytics, history, or further processing. Adapt the code to your use case and enjoy building smarter apps!