diff --git a/api-reference.mdx b/api-reference.mdx new file mode 100644 index 0000000..c80eee1 --- /dev/null +++ b/api-reference.mdx @@ -0,0 +1,188 @@ +# API Reference + +This document provides a comprehensive reference for all public-facing interfaces that form part of the **Next.js Chatbot with Gemini AI** stack. +Endpoints are organised by functional area; each entry lists its HTTP verb, expected request schema, successful response payload, and possible error conditions. + +--- + +## Contents + +1. Authentication (`/api/auth/*`) +2. Chat (`/api/chat`) +3. Environment Variables +4. Client-side Utility Functions (`lib/*`) +5. Types + +--- + +## 1. Authentication Endpoints (`/api/auth/*`) + +The application employs **NextAuth.js** with the Google OAuth provider. All authentication routes are created automatically by NextAuth and therefore follow the conventional path structure. + +| Path | Verb | Description | +|------|------|-------------| +| `/api/auth/signin` | `GET` | Presents the Google OAuth consent page. | +| `/api/auth/callback/google`| `GET` | OAuth2.0 redirect URI—exchanges the authorisation code for tokens and issues a session cookie. | +| `/api/auth/session` | `GET` | Retrieves the current session object. | +| `/api/auth/signout` | `POST` | Invalidates the current session. | + +### Session Object + +```jsonc +{ + "user": { + "id": "string", // Google user id + "name": "string", + "email": "string", + "image": "string" + }, + "expires": "ISO-8601 timestamp" +} +``` + +### Error Codes + +| Status | Meaning | Notes | +|--------|-----------------------------|-------------------------------------| +| `401` | Unauthenticated | Session cookie missing or invalid. | +| `500` | Internal Server Error | Upstream Google OAuth failure. | + +--- + +## 2. Chat Endpoint (`/api/chat`) + +Handles all interactions with **Google Gemini AI**. This route is manually implemented and therefore version-controlled inside `app/api/chat/route.ts`. + +### `POST /api/chat` + +| Attribute | Value | +|-----------|----------------------------------| +| Auth | Required (active NextAuth session) | +| MIME | `application/json` | + +#### Request Body + +```jsonc +{ + "messages": [ + { + "role": "user" | "assistant" | "system", + "content": "string" // Plain-text message + } + ] +} +``` + +*The `messages` array must include at least one user message and may include the full conversation history so that Gemini can provide contextually-aware responses.* + +#### Successful Response `200 OK` + +```jsonc +{ + "id": "string", // Server-generated uuid + "createdAt": 1710760200, // Unix epoch (seconds) + "choices": [ + { + "index": 0, + "message": { + "role": "assistant", + "content": "string" // Gemini's reply + } + } + ] +} +``` + +#### Error Responses + +| Status | Meaning | Typical Cause | +|--------|--------------------------------|--------------------------------------------------| +| `400` | Bad Request | Malformed JSON or missing `messages`. | +| `401` | Unauthenticated | Absent/expired NextAuth session. | +| `429` | Rate Limit Exceeded | Gemini quota exhausted. | +| `500` | Internal Server Error | Upstream Gemini failure or configuration issue. | + +--- + +## 3. Environment Variables + +All sensitive configuration values are managed through `.env.local` (development) or the hosting provider’s secret store (production). + +| Variable | Description | +|----------|--------------------------------------------------| +| `GOOGLE_CLIENT_ID` | Google OAuth client ID. | +| `GOOGLE_CLIENT_SECRET` | Google OAuth client secret. | +| `NEXTAUTH_URL` | Absolute URL of the site (e.g. `https://app.tld`).| +| `NEXTAUTH_SECRET` | Random string used to sign JWT/session cookies. | +| `GEMINI_API_KEY` | Server key for Gemini API access. | + +> **Tip:** In **Vercel**, add these under *Project Settings → Environment Variables* and mark them as **Encrypted**. + +--- + +## 4. Client-side & Server-side Utilities + +### `lib/auth.ts` + +Utility helpers that wrap `getServerSession` and type-safe session extraction. + +```ts +export const requireSession = async () => { + const session = await getServerSession(authOptions); + if (!session) throw new Error("Unauthenticated"); + return session; +}; +``` + +### `lib/gemini.ts` + +Thin wrapper around the official Gemini SDK. + +```ts +export const askGemini = async (messages: GeminiMessage[]) => { + const client = new Gemini({ + apiKey: process.env.GEMINI_API_KEY! + }); + return client.chat({ messages }); +}; +``` + +### `lib/utils.ts` + +Shared helper functions (e.g. UUID generation, date formatting, local-storage handlers). All functions are fully typed with **TypeScript** generics and JSDoc comments. + +--- + +## 5. Types (`types/*`) + +A centralised location for domain-specific TypeScript interfaces. + +```ts +export interface ChatMessage { + role: "user" | "assistant" | "system"; + content: string; +} + +export interface ChatResponse { + id: string; + createdAt: number; + choices: { index: number; message: ChatMessage }[]; +} +``` + +--- + +## Versioning + +This document tracks the `main` branch at commit `HEAD`. Breaking changes will trigger a semantic version bump in `package.json`. + +--- + +## Feedback + +Encountered an inconsistency or missing field? +Please open an issue or submit a pull request referencing this page so that the documentation remains accurate and exhaustive. + +--- + +© Next.js Chatbot with Gemini AI — Released under the **MIT License**. \ No newline at end of file diff --git a/configuration.mdx b/configuration.mdx new file mode 100644 index 0000000..8eb353b --- /dev/null +++ b/configuration.mdx @@ -0,0 +1,164 @@ +# Configuration Guide + +This document explains **all mandatory configuration steps** required to run the **Next.js Chatbot with Gemini AI** in both local-development and production environments. +Follow the sections in the order presented to guarantee a smooth installation and deployment experience. + +--- + +## 1. Prerequisites + +| Requirement | Minimum Version | Notes | +|-------------|-----------------|-------| +| Node.js | 18 LTS | The application is written in TypeScript and targets modern ECMAScript features available in Node 18+. | +| Google Cloud Project | — | The project must have the **Gemini API** enabled and Google OAuth credentials created. | +| Package Manager | npm, Yarn, or pnpm | Choose any; all lock-files are ignored in `.gitignore`. | + +> **Tip** +> Although the project works on any platform that supports Node.js, macOS 12+, Ubuntu 20.04 LTS, or Windows 11 WSL 2 are the combinations tested during development. + +--- + +## 2. Repository Setup + +Clone the repository and install dependencies: + +```bash +git clone https://github.com//nextjs-gemini-chatbot.git +cd nextjs-gemini-chatbot + +# npm +npm install + +# — or — + +# yarn +yarn install + +# — or — + +# pnpm +pnpm install +``` + +--- + +## 3. Environment Variables (`.env.local`) + +All sensitive values are stored in a local file named **`.env.local`** at the project root. +Create the file (it is **git-ignored** by default) and insert the following keys: + +```bash +# ──────────────── Google OAuth ──────────────── +GOOGLE_CLIENT_ID = your_google_client_id +GOOGLE_CLIENT_SECRET = your_google_client_secret + +# ──────────────── NextAuth ──────────────── +NEXTAUTH_URL = http://localhost:3000 +NEXTAUTH_SECRET = a_long_random_string + +# ──────────────── Gemini API ──────────────── +GEMINI_API_KEY = your_gemini_api_key +``` + +### 3.1 Generating `NEXTAUTH_SECRET` + +Generate a cryptographically-secure random string: + +```bash +openssl rand -base64 32 +``` + +Paste the value in the `NEXTAUTH_SECRET` field. + +--- + +## 4. Google Cloud Console Configuration + +1. Sign in to **https://console.cloud.google.com** and open (or create) a project. +2. Navigate to **APIs & Services → Library**, search for **Gemini API**, and click **Enable**. +3. Under **Credentials** create an **OAuth 2.0 Client ID** of type **Web Application** and fill in: + + | Field | Value | + |-------|-------| + | **Authorized JavaScript origins** | `http://localhost:3000` | + | **Authorized redirect URIs** | `http://localhost:3000/api/auth/callback/google` | + +4. Download the JSON or copy the `client_id` and `client_secret` and update `.env.local`. + +--- + +## 5. Local Development + +Run the development server: + +```bash +npm run dev +# or: yarn dev +# or: pnpm dev +``` + +Open **http://localhost:3000**. +On first load you will be prompted to sign in with Google. After successful authentication, start chatting with the Gemini-powered assistant. Chat history is persisted automatically in browser **Local Storage**. + +--- + +## 6. Production Deployment + +Although any platform that supports Next.js 14+ works, **Vercel** is the recommended target. + +### 6.1 Deploying to Vercel + +1. Push your repository to GitHub, GitLab, or Bitbucket. +2. Sign in to **https://vercel.com** and import the project. +3. In the **Environment Variables** panel replicate the keys in the local `.env.local`. +4. Click **Deploy** – Vercel detects the framework, runs `pnpm build` (or the appropriate command), and serves the application globally. + +### 6.2 Alternative Platforms + +For platforms such as Netlify, Render, DigitalOcean, or a custom VPS: + +1. Set `NODE_ENV=production` and build the project: `npm run build`. +2. Expose the same environment variables shown in Section 3. +3. Serve the app with `npm start`, or with a process manager such as **PM2**. + +--- + +## 7. Troubleshooting + +| Symptom | Possible Cause | Resolution | +|---------|----------------|------------| +| Google sign-in shows “Error 400: redirect_uri_mismatch” | Redirect URI not whitelisted | Add `http:///api/auth/callback/google` to Google OAuth redirect URIs. | +| Gemini API returns **401 Unauthorized** | Incorrect or missing `GEMINI_API_KEY` | Verify the key in **https://console.cloud.google.com** and `.env.local`. | +| Blank page after build | Missing `NEXTAUTH_URL` in production | Set `NEXTAUTH_URL` to your live domain (e.g., `https://chatbot.example.com`). | + +--- + +## 8. Updating Configuration + +When changing any value in `.env.local`: + +1. Stop the development server (`CTRL + C`). +2. Update the variables. +3. Restart the server to apply the new configuration. + +For production, re-deploy the application after editing environment variables. + +--- + +## 9. Further Reading + +- Next.js Environment Variables + https://nextjs.org/docs/app/building-your-application/configuring/environment-variables + +- NextAuth.js Configuration + https://next-auth.js.org/configuration/options + +- Google Cloud OAuth 2.0 + https://developers.google.com/identity/protocols/oauth2 + +- Gemini API Documentation + https://cloud.google.com/ai/gemini/docs + +--- + +© MIT License — © 2024 The Next.js Gemini Chatbot Contributors \ No newline at end of file diff --git a/deployment.mdx b/deployment.mdx new file mode 100644 index 0000000..a258e1b --- /dev/null +++ b/deployment.mdx @@ -0,0 +1,154 @@ +# Deployment Guide + +This document explains how to deploy the **Next.js Chatbot with Gemini AI** to production. +While any platform capable of running a Node.js application can host the project, the recommended solution is **Vercel**, which offers first-class support for Next.js and a friction-less CI/CD experience. + +--- + +## 1. Prerequisites + +Before initiating a production deployment, ensure that the following requirements are satisfied: + +| Requirement | Minimum Version | Notes | +|-------------|-----------------|-------| +| Node.js | 18 .x | Used by the build pipeline. The hosting platform must supply an equivalent or later runtime. | +| npm / pnpm / yarn | Latest stable | The lock file (`package-lock.json`, `pnpm-lock.yaml`, or `yarn.lock`) should be committed to guarantee deterministic builds. | +| Google Cloud project | — | Gemini API **enabled** and OAuth credentials created. | +| Environment variables | — | See section 4. | + +--- + +## 2. Deployment on Vercel (Recommended) + +Vercel provides zero-configuration support for Next.js, automatic preview environments, and seamless integration with GitHub, GitLab, or Bitbucket repositories. + +### 2.1. Step-by-Step + +1. **Push the code to a Git repository** + ```bash + git remote add origin + git push -u origin main + ``` + +2. **Create a new Vercel project** + - Sign in to [Vercel](https://vercel.com/). + - Select **New Project** → **Import** your repository. + +3. **Configure environment variables** + Inside the *Environment Variables* tab, add the following keys for the **Production**, **Preview**, and **Development** environments. + + | Key | Example Value | + |-----|---------------| + | `GOOGLE_CLIENT_ID` | `xxxxxxxxxx.apps.googleusercontent.com` | + | `GOOGLE_CLIENT_SECRET` | `yoursecret` | + | `NEXTAUTH_URL` | `https://your-vercel-domain.vercel.app` | + | `NEXTAUTH_SECRET` | `long-random-string` | + | `GEMINI_API_KEY` | `gemini-api-key` | + +4. **Deploy** + Click **Deploy**. Vercel will execute `npm run build` (or the equivalent pnpm/yarn command) and host the generated application. + +### 2.2. Post-Deployment Checklist + +- **Update Google OAuth authorised domains** + In the Google Cloud Console, add your Vercel production and preview domains to + `Authorised JavaScript origins` **and** + `Authorised redirect URIs` (`https:///api/auth/callback/google`). + +- **Verify build output** + Use Vercel’s preview URL to confirm that: + - Google sign-in works. + - A test conversation with the chatbot returns responses. + - Chat history persists after a page reload. + +--- + +## 3. Deploying to Other Platforms + +Although Vercel is recommended, any Node-compatible hosting service (Netlify, Render, AWS Amplify, Fly.io, Heroku, etc.) can serve the application. + +| Task | Command / Setting | +|------|-------------------| +| **Install dependencies** | `npm install` (or `pnpm install`, `yarn install`) | +| **Build** | `npm run build` | +| **Start** (Serverless target) | Many platforms detect the Next.js output automatically. For traditional Node hosting use `npm start` or `next start`. | +| **Environment variables** | Same keys as listed in section 2.1. | + +> **Tip:** When using a custom server or Docker, ensure that port **3000** is exposed and that your health checks target `/`. + +--- + +## 4. Environment Variables (Reference) + +| Variable | Description | +|----------|-------------| +| `GOOGLE_CLIENT_ID` | OAuth 2.0 client ID obtained from Google Cloud Console. | +| `GOOGLE_CLIENT_SECRET` | OAuth 2.0 client secret corresponding to the client ID. | +| `NEXTAUTH_URL` | Absolute URL of the deployed site (e.g., `https://chatbot.example.com`). | +| `NEXTAUTH_SECRET` | A random string used by NextAuth.js to sign JWTs and cookies. | +| `GEMINI_API_KEY` | API key that authorises requests to the Gemini language model. | + +Store these values securely; never commit them to the repository. + +--- + +## 5. Continuous Integration / Continuous Deployment + +The repository includes no platform-specific CI configuration, allowing each hosting provider to apply its own defaults. If you prefer an explicit pipeline: + +```yaml +# .github/workflows/deploy.yml (example) +name: Deploy + +on: + push: + branches: [main] + +jobs: + build-and-deploy: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + - uses: pnpm/action-setup@v2 + with: + version: 8 + - name: Install + run: pnpm install + - name: Build + run: pnpm run build + - name: Deploy to Vercel + uses: amondnet/vercel-action@v25 + with: + vercel-token: ${{ secrets.VERCEL_TOKEN }} + vercel-org-id: ${{ secrets.VERCEL_ORG_ID }} + vercel-project-id: ${{ secrets.VERCEL_PROJECT_ID }} +``` + +--- + +## 6. Troubleshooting + +| Symptom | Possible Cause | Resolution | +|---------|----------------|------------| +| *“Invalid `NEXTAUTH_URL`”* | Environment variable missing or misspelled | Verify the variable in the hosting dashboard. | +| *OAuth consent screen error* | Redirect URI not whitelisted | Add the exact URI to the Google Cloud Console. | +| *Gemini API 4xx/5xx* | Invalid or expired `GEMINI_API_KEY` | Regenerate the key in Google Cloud and redeploy. | +| *Blank page after deploy* | Build failed or static assets missing | Inspect build logs, ensure `next build` succeeds locally. | + +--- + +## 7. Support + +For deployment-related questions: + +1. Review this documentation thoroughly. +2. Search existing issues in the GitHub repository. +3. If the problem persists, open a **new issue** providing: + - Hosting provider + - Build logs + - Browser console output + - Steps to reproduce + +--- + +© MIT License – see `LICENSE` for full details. \ No newline at end of file diff --git a/getting-started.mdx b/getting-started.mdx new file mode 100644 index 0000000..e2009d4 --- /dev/null +++ b/getting-started.mdx @@ -0,0 +1,180 @@ +# Getting Started + +Welcome to **Next.js Chatbot with Gemini AI** – a modern, production-ready chatbot application that combines the power of **Next.js 14+ (App Router)**, **Google Gemini AI**, and **NextAuth.js** with Google OAuth. +This document provides an end-to-end guide for setting-up, configuring, and operating the project. + +--- + +## 1. Features Overview + +- **AI-Powered Conversations** – Natural-language processing through Google Gemini API. +- **Google Authentication** – Secure, OAuth 2.0-based sign-in via NextAuth.js. +- **Persistent History** – Conversations are cached in browser Local Storage. +- **Responsive UI** – Optimised for both desktop and mobile devices. +- **Real-Time Interaction** – Smooth, interactive chat interface with typing indicators. + +--- + +## 2. Technology Stack + +| Layer | Technology | +| ------------------ | -------------------------------------------- | +| Framework | **Next.js 14+** (App Router, Server Actions) | +| Authentication | **NextAuth.js** (Google Provider) | +| AI Integration | **Google Gemini API** | +| Styling | **Tailwind CSS** (customisable) | +| Storage | Browser **Local Storage** | +| Language/Tooling | **TypeScript** | + +--- + +## 3. Prerequisites + +Before cloning or running the application, ensure the following: + +1. **Node.js ≥ 18** installed locally. +2. An active **Google Cloud Project** with the **Gemini API** enabled. +3. **Google OAuth 2.0** credentials (Client ID & Secret). + +--- + +## 4. Environment Variables + +Create a file named `.env.local` in the project root and supply the variables below: + +```env +# ── Google OAuth ─────────────────────────────────────────────── +GOOGLE_CLIENT_ID=your_google_client_id +GOOGLE_CLIENT_SECRET=your_google_client_secret + +# ── NextAuth ─────────────────────────────────────────────────── +NEXTAUTH_URL=http://localhost:3000 +NEXTAUTH_SECRET=your_nextauth_secret + +# ── Gemini API ───────────────────────────────────────────────── +GEMINI_API_KEY=your_gemini_api_key +``` + +> Never commit real secrets to version control. +> When deploying, add the same keys in your hosting provider’s dashboard (e.g., **Vercel → Project Settings → Environment Variables**). + +--- + +## 5. Installation + +```bash +# 1. Clone the repository +git clone https://github.com//nextjs-gemini-chatbot.git +cd nextjs-gemini-chatbot + +# 2. Install dependencies +npm install # or: yarn install / pnpm install + +# 3. Run the development server +npm run dev # or: yarn dev / pnpm dev +``` + +Open `http://localhost:3000` in your browser – the application will hot-reload as you modify source files. + +--- + +## 6. Google Cloud & OAuth Configuration + +1. Sign in to **Google Cloud Console** and select / create a project. +2. Navigate to **APIs & Services → Library** and enable **Gemini API**. +3. Under **Credentials → Create Credentials → OAuth Client ID**: + - Application Type: **Web Application** + - Authorised *JavaScript Origin*: `http://localhost:3000` + - Authorised *Redirect URI*: `http://localhost:3000/api/auth/callback/google` +4. Copy the generated **Client ID** and **Client Secret** into `.env.local`. + +--- + +## 7. Project Structure + +``` +├── app/ +│ ├── api/ +│ │ ├── auth/ # NextAuth handlers +│ │ └── chat/ # Gemini chat endpoint +│ ├── components/ # Reusable UI components +│ ├── page.tsx # Landing / chat page +│ └── layout.tsx # Root layout +├── lib/ +│ ├── auth.ts # Auth helpers +│ ├── gemini.ts # Gemini SDK wrapper +│ └── utils.ts # Shared utilities +├── types/ # Type declarations +└── public/ # Static assets +``` + +--- + +## 8. Usage + +### 8.1 User Flow + +1. **Authenticate** – Users sign-in with Google. +2. **Start Chatting** – Send messages; responses are generated by Gemini AI. +3. **Persistent History** – Chats are saved locally and rehydrated on page load. +4. **Session Continuity** – Auth & chats persist across browser sessions. + +### 8.2 API Endpoints + +| Path | Purpose | +| ----------------- | --------------------------------------------- | +| `/api/auth/*` | NextAuth.js authentication routes | +| `/api/chat` | Proxy endpoint to Gemini API for chat replies | + +--- + +## 9. Deployment + +### 9.1 Vercel (Recommended) + +1. Push your code to **GitHub** (or GitLab). +2. Import the repository in **Vercel**. +3. Configure **Environment Variables** in *Project → Settings → Environment Variables*. +4. Click **Deploy** – Vercel will build and host automatically. + +### 9.2 Other Platforms + +The application is platform-agnostic; configure build commands (`next build`), start commands (`next start`), and environment variables according to your provider. + +--- + +## 10. Contributing + +Contributions are welcome: + +1. **Fork** the repository. +2. Create a **feature branch** (`git checkout -b feat/my-feature`). +3. Commit your changes with clear messages. +4. **Open a Pull Request** against the `main` branch. + +--- + +## 11. License + +Distributed under the **MIT License**. See `LICENSE` for full text. + +--- + +## 12. Support & Contact + +- Open an **Issue** on GitHub for bug reports or feature requests. +- Review this documentation for common setup and usage questions. + +--- + +## 13. Acknowledgements + +- **Google Gemini AI** – advanced language processing. +- **Next.js** – robust React framework. +- **NextAuth.js** – seamless authentication. + +> *“This is one of the most amazing applications planet Earth has seen. In sha Allah.”* + +--- + +Happy building! \ No newline at end of file