Build and Deploy a Full-Stack LLM Feature with TypeScript and Vercel
Learn to build and deploy a simple full-stack LLM feature using modern TypeScript for both frontend and backend on Vercel.
Building AI-powered features often means integrating Large Language Models (LLMs) into existing applications. This requires both a frontend for user interaction and a backend to handle the LLM API calls securely and efficiently. Modern web development stacks offer a streamlined way to achieve this. Using TypeScript and Vercel provides a robust, scalable, and developer-friendly environment for shipping these features quickly.
This guide outlines how to build a basic full-stack LLM feature, from the user interface to the LLM API call, and deploy it.
Project Structure for LLM Features
A full-stack LLM feature typically separates concerns. The frontend handles user input and displays results. The backend acts as a secure intermediary, calling the LLM API and processing responses. This separation is critical for several reasons:
- Security: LLM API keys must remain server-side. Exposing them in client-side code is a significant security risk.
- Performance: Backend logic can optimize API calls, handle retries, and manage rate limits.
- Scalability: Serverless functions, like Vercel's Edge Functions, scale automatically with demand.
- Complexity: Keeping LLM interaction logic separate from UI logic simplifies debugging and maintenance.
For a simple feature, a Next.js project is a good fit. It provides both the frontend framework and an API route system within a single repository.
Building the API with Vercel Edge Functions
Vercel Edge Functions are ideal for LLM API proxies. They execute close to your users, reducing latency. They are also serverless, meaning you only pay for what you use, and they scale automatically.
Here is a basic example of an Edge Function written in TypeScript. This function takes a user's prompt, sends it to an LLM, and returns the generated text.
Create a file at pages/api/generate.ts (for Pages Router) or app/api/generate/route.ts (for App Router) in your Next.js project. We'll use a generic LLM client for demonstration.
// pages/api/generate.ts (or app/api/generate/route.ts for App Router)
import type { NextRequest } from 'next/server';
// Placeholder for your actual LLM client, e.g., from OpenAI, Anthropic, etc.
// You would install the specific client library for your chosen LLM.
interface LLMClient {
chat: {
completions: {
create: (params: { model: string; messages: { role: string; content: string }[] }) => Promise<{ choices: { message: { content: string } }[] }>;
};
};
}
// This is a mock client for demonstration. Replace with your actual LLM client setup.
const mockLlmClient: LLMClient = {
chat: {
completions: {
create: async (params) => {
console.log("Calling mock LLM with:", params.messages);
// Simulate an LLM response
const lastMessage = params.messages[params.messages.length - 1].content;
const responseContent = `This is a generated response based on: "${lastMessage}"`;
return { choices: [{ message: { content: responseContent } }] };
},
},
},
};
export const config = {
runtime: 'edge',
};
export default async function handler(req: NextRequest) {
if (req.method !== 'POST') {
return new Response(JSON.stringify({ error: 'Method Not Allowed' }), { status: 405 });
}
const { prompt } = await req.json();
if (!prompt) {
return new Response(JSON.stringify({ error: 'Prompt is required' }), { status: 400 });
}
try {
// In a real application, you would use your actual LLM client here.
// For example: const response = await openai.chat.completions.create(...);
const llmResponse = await mockLlmClient.chat.completions.create({
model: 'your-preferred-llm-model',
messages: [{ role: 'user', content: prompt }],
});
const generatedText = llmResponse.choices[0].message.content;
return new Response(JSON.stringify({ result: generatedText }), {
status: 200,
headers: { 'Content-Type': 'application/json' },
});
} catch (error) {
console.error('LLM API error:', error);
return new Response(JSON.stringify({ error: 'Failed to generate content' }), { status: 500 });
}
}
Remember to replace mockLlmClient with your actual LLM integration. For example, if using OpenAI, you would import OpenAI from 'openai'; and instantiate const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });.
Frontend Integration with React/Next.js
On the frontend, you need a way for users to input their prompt and display the LLM's response. A simple React component can handle this. This example uses useState for managing input and output, and fetch to call the API route.
// pages/index.tsx (or a client component in app/ for App Router)
import { useState } from 'react';
export default function Home() {
const [prompt, setPrompt] = useState('');
const [response, setResponse] = useState('');
const [loading, setLoading] = useState(false);
const [error, setError] = useState('');
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setLoading(true);
setResponse('');
setError('');
try {
const res = await fetch('/api/generate', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ prompt }),
});
if (!res.ok) {
const errorData = await res.json();
throw new Error(errorData.error || 'Something went wrong');
}
const data = await res.json();
setResponse(data.result);
} catch (err: any) {
setError(err.message);
} finally {
setLoading(false);
}
};
return (
<div style={{ padding: '2rem', maxWidth: '600px', margin: 'auto' }}>
<h1>LLM Feature Demo</h1>
<form onSubmit={handleSubmit}>
<textarea
value={prompt}
onChange={(e) => setPrompt(e.target.value)}
placeholder="Enter your prompt here..."
rows={5}
style={{ width: '100%', marginBottom: '1rem', padding: '0.5rem' }}
/>
<button type="submit" disabled={loading || !prompt.trim()}>
{loading ? 'Generating...' : 'Generate'}
</button>
</form>
{error && <p style={{ color: 'red' }}>Error: {error}</p>}
{response && (
<div style={{ marginTop: '2rem', borderTop: '1px solid #eee', paddingTop: '1rem' }}>
<h2>Response:</h2>
<p>{response}</p>
</div>
)}
</div>
);
}
This component provides a basic text area for input, a button to trigger the generation, and displays the result. It also handles loading states and errors, improving the user experience.
Environment Variables and Security
LLM API keys are sensitive. Never hardcode them. Vercel provides a secure way to manage environment variables.
Local Development: Create a
.env.localfile in your project root.OPENAI_API_KEY=sk-yourlocaltestkeyAccess this in your API routes using
process.env.OPENAI_API_KEY.Vercel Deployment: Go to your project settings in the Vercel dashboard. Navigate to "Environment Variables" and add your production API keys there. Mark them as "Encrypted" if available. Vercel automatically injects these into your Edge Functions during deployment.
This approach keeps your sensitive keys out of your codebase and allows different keys for development and production environments.
Deployment to Vercel
Deploying a Next.js application to Vercel is straightforward. Vercel integrates directly with Git repositories (GitHub, GitLab, Bitbucket).
- Push to Git: Ensure your project is pushed to a Git repository.
- Import Project: In the Vercel dashboard, import your Git repository as a new project.
- Configure: Vercel automatically detects Next.js projects and sets up sensible defaults. You can specify a root directory if your project is in a monorepo.
- Deploy: Once configured, Vercel will deploy your application. Every subsequent
git pushto your main branch triggers a new production deployment. Pushes to other branches create preview deployments.
Vercel handles the build process, serves your static assets, and deploys your Edge Functions globally. This means your full-stack LLM feature is accessible and performs well for users worldwide without manual server management.
Where to go from here
Start by implementing this basic structure with your chosen LLM and iterating on the user experience. Consider adding more robust error handling, streaming responses, or integrating more complex LLM workflows. If you need expert guidance, consider our AI consulting services.