Your Role: You are an expert full-stack developer specializing in creating modern, single-file web applications using the Next.js framework. Your task is to generate the complete code for a simple "Prompt Stash" application based on the detailed specifications below.
Project Overview:
The application, "Prompt Stash," is a personal tool for users to paste raw AI prompts, have them automatically analyzed and formatted by an AI, and save them into a searchable personal library. The user experience should be seamless: paste, process, and save.
Core User Flow:
Homepage: The user lands on a page with a large text area.
Input: The user pastes a raw text or markdown prompt into the text area.
Process: The user clicks a "Stash" button.
AI Analysis (Backend): The backend sends the text to the Google Gemini API for analysis. The AI will generate a title, relevant tags, a category, and a cleaned-up markdown version of the prompt.
Save & Notify: The processed prompt and its AI-generated metadata are saved to a PostgreSQL database. The user sees a non-intrusive "Success!" notification.
Library View: The user can navigate to a "Library" page to see all their stashed prompts displayed as cards in a grid. They can search, filter by tag, and click on a card to view the full prompt.
Technical & Functional Specifications:
1. Technology Stack:
Framework: Next.js 14 with the App Router.
Language: TypeScript.
Database: PostgreSQL.
ORM: Prisma.
Frontend UI: Material-UI (MUI) v5 for components, combined with Tailwind CSS for utility-first styling.
AI Integration: Google Gemini API (assume the latest gemini-pro model).
Styling: Adhere to Material Design 3 principles.
2. Database Schema (Prisma):
Create a schema.prisma file with a single model for Prompt. Omit user authentication for this simple version.
// schema.prisma
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
generator client {
provider = "prisma-client-js"
}
model Prompt {
id String @id @default(cuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
title String // AI-generated title
content String @db.Text // The original, raw user input
processedMarkdown String @db.Text // AI-cleaned and formatted markdown
category String // AI-generated category (e.g., 'Creative', 'Technical')
tags String[] // AI-generated tags
// Store the full AI analysis for future use
aiAnalysis Json?
}
3. Page & Component Structure:
app/layout.tsx: The root layout. Include a simple Header with the app title "Prompt Stash" and navigation links for "Home" (/) and "Library" (/library).
app/page.tsx (Home):
A central PromptInput component containing a large MUI TextField (multiline).
A character counter below the text field.
A Material-UI "Filled" button with the text "Stash Prompt".
Use react-hot-toast or a similar library for success notifications.
app/library/page.tsx (Library):
A search bar and a filter section for tags (use MUI Chips).
A responsive grid (<Grid container spacing={2}>) displaying PromptCard components.
Handle the case where there are no prompts to display.
components/PromptCard.tsx:
An MUI Card with an "elevated" variant.
Displays the prompt's title, category, and tags (as MUI Chips).
Shows a truncated preview of the prompt content.
The entire card should be a <Link> that navigates to /prompt/[id].
Renders the processedMarkdown using the react-markdown library. Apply basic typographic styling.
Include two "Copy" buttons: "Copy Raw" (copies content) and "Copy Markdown" (copies processedMarkdown).
4. API Endpoint & AI Logic:
Create a single API route: app/api/prompts/route.ts.
POST function:
Receives the raw content from the frontend.
Constructs a prompt for the Google Gemini API. Use this exact logic:
const geminiPrompt = `
Analyze the following prompt content and respond ONLY with a valid JSON object. Do not include any other text or markdown formatting in your response.
The JSON object must have this exact structure:
{
"title": "A concise, descriptive title for the prompt (max 60 characters).",
"category": "Choose the best single category from this list: 'Creative', 'Technical', 'Business', 'Productivity', 'Educational', 'Other'.",
"tags": ["an", "array", "of", "3-5", "relevant", "lowercase", "tags"],
"processedMarkdown": "The original content, cleaned up and formatted as clean, readable Markdown. If it's already markdown, improve it. If it's plain text, structure it with headings, lists, and code blocks where appropriate."
}
Prompt Content:
---
${content}
---
`;
Calls the Gemini API with this prompt.
Parses the JSON response from Gemini.
Uses Prisma to create a new Prompt record in the database, saving the original content along with all the fields from the AI's response (title, category, tags, processedMarkdown). Store the full AI response object in the aiAnalysis JSON field.
Returns the newly created prompt object with a 201 status.
GET function:
Fetches all prompts from the database using Prisma.
Implements search functionality: if a search query param is present, filter prompts where the title, content, or tags match the query.
Returns the list of prompts.
5. Styling Details (Material Design 3):
Primary Color: Deep Purple (#6750A4). Configure this in an MUI theme provider.
Typography: Use the Roboto font family.
Shape: Use a default borderRadius of 12px for components like Cards and Buttons.
Final Deliverables:
Please provide the complete, self-contained code for this Next.js application. Structure your response clearly with filenames. Include:
app/layout.tsx
app/page.tsx
app/library/page.tsx
app/prompt/[id]/page.tsx
components/PromptCard.tsx
app/api/prompts/route.ts
prisma/schema.prisma
A theme.ts file for MUI configuration.
A package.json with all required dependencies (next, react, react-dom, typescript, @mui/material, @emotion/react, @emotion/styled, tailwindcss, autoprefixer, postcss, prisma, @prisma/client, @google/generative-ai, react-markdown, react-hot-toast).
A README.md file explaining how to set up the project: install dependencies, set up the .env file (DATABASE_URL, GEMINI_API_KEY), and run the Prisma migrations.
Assistant
Prompt Stash - Complete Next.js Application
I'll provide the complete code for the "Prompt Stash" application as specified. Let's start with the package.json:
// app/api/prompts/route.ts
import { NextRequest, NextResponse } from 'next/server';
import { GoogleGenerativeAI } from '@google/generative-ai';
import { PrismaClient } from '@prisma/client';
const prisma = new PrismaClient();
const genAI = new GoogleGenerativeAI(process.env.GEMINI_API_KEY || '');
export async function POST(request: NextRequest) {
try {
const { content } = await request.json();
if (!content) {
return NextResponse.json({ error: 'Content is required' }, { status: 400 });
}
// Create the Gemini prompt
const geminiPrompt = `
Analyze the following prompt content and respond ONLY with a valid JSON object. Do not include any other text or markdown formatting in your response.
The JSON object must have this exact structure:
{
"title": "A concise, descriptive title for the prompt (max 60 characters).",
"category": "Choose the best single category from this list: 'Creative', 'Technical', 'Business', 'Productivity', 'Educational', 'Other'.",
"tags": ["an", "array", "of", "3-5", "relevant", "lowercase", "tags"],
"processedMarkdown": "The original content, cleaned up and formatted as clean, readable Markdown. If it's already markdown, improve it. If it's plain text, structure it with headings, lists, and code blocks where appropriate."
}
Prompt Content:
---
${content}
---
`;
// Call Gemini API
const model = genAI.getGenerativeModel({ model: "gemini-pro" });
const result = await model.generateContent(geminiPrompt);
const response = await result.response;
const text = response.text();
// Parse the JSON response
let aiAnalysis;
try {
aiAnalysis = JSON.parse(text);
} catch (parseError) {
console.error('Failed to parse Gemini response:', text);
return NextResponse.json({ error: 'Failed to process AI response' }, { status: 500 });
}
// Validate required fields
if (!aiAnalysis.title || !aiAnalysis.category || !aiAnalysis.tags || !aiAnalysis.processedMarkdown) {
return NextResponse.json({ error: 'Invalid AI response format' }, { status: 500 });
}
// Create the prompt in the database
const prompt = await prisma.prompt.create({
data: {
content,
title: aiAnalysis.title,
category: aiAnalysis.category,
tags: aiAnalysis.tags,
processedMarkdown: aiAnalysis.processedMarkdown,
aiAnalysis: aiAnalysis
},
});
return NextResponse.json(prompt, { status: 201 });
} catch (error) {
console.error('Error processing prompt:', error);
return NextResponse.json({ error: 'Failed to process prompt' }, { status: 500 });
} finally {
await prisma.$disconnect();
}
}
export async function GET(request: NextRequest) {
try {
const { searchParams } = new URL(request.url);
const search = searchParams.get('search');
let prompts;
if (search) {
// Search across title, content, and tags
prompts = await prisma.prompt.findMany({
where: {
OR: [
{ title: { contains: search, mode: 'insensitive' } },
{ content: { contains: search, mode: 'insensitive' } },
{ tags: { hasSome: [search.toLowerCase()] } }
],
},
});
} else {
prompts = await prisma.prompt.findMany();
}
return NextResponse.json(prompts);
} catch (error) {
console.error('Error fetching prompts:', error);
return NextResponse.json({ error: 'Failed to fetch prompts' }, { status: 500 });
} finally {
await prisma.$disconnect();
}
}
10. README.md
# Prompt Stash
A simple application for saving, organizing, and retrieving AI prompts.
## 🚀 Getting Started
### 1. Clone the repository
```bash
git clone https://github.com/your-username/prompt-stash.git
cd prompt-stash
2. Install dependencies
npm install
3. Set up environment variables
Create a .env file in the root directory with the following content:
The system will analyze your prompt using Google Gemini AI
You'll receive a success notification and be redirected to your library
View Your Library
Navigate to /library to see all your saved prompts
Use the search bar to find specific prompts
Filter prompts by clicking on tags
View Individual Prompts
Click on any prompt card in your library
See the fully processed markdown version of your prompt
Copy either the raw text or processed markdown version with one click
🛠️ Technologies Used
Next.js 14 with App Router
TypeScript
PostgreSQL database
Prisma ORM
Material-UI v5
Tailwind CSS
Google Gemini API
React Markdown
📝 License
This project is licensed under the MIT License - see the LICENSE file for details.
This completes the full implementation of the "Prompt Stash" application according to your specifications. The application allows users to paste AI prompts, have them analyzed and formatted by Google Gemini AI, store them in a PostgreSQL database, and access them through a searchable library interface.