# Next JS

### 1. Setup JamAIBase project.

* Create a new project.

<figure><img src="/files/5M9oiKI0E3n5r3G7VQS8" alt=""><figcaption></figcaption></figure>

* Get the **Project ID**.

<div align="left"><figure><img src="/files/fCTA3D88NegoHPgQt4zk" alt=""><figcaption></figcaption></figure></div>

* Create **JamAI API Key** at **Organization > Secrets > Create API Key.**

<figure><img src="/files/00s4EbZhIkZer0XMsuoY" alt=""><figcaption></figcaption></figure>

### 2. Create Table

We will fetch table data and display on our Next.js application. If your project is empty, you can create new table through our UI on <https://cloud.jamaibase.com> or through the API:

```bash
curl 'https://api.jamaibase.com/api/v1/gen_tables/action' \
    -H "Authorization: Bearer <your-jamai-api-key>" \
    -H "X-PROJECT-ID: <project-id>" \
    -H 'Content-Type: application/json' \
    --data-raw '{"id":"CountryCapital","cols":[{"id":"Country","dtype":"str","index":false,"gen_config":null},{"id":"Capital City","dtype":"str","index":false,"gen_config":{"model":"ellm/meta-llama/Llama-3-8B-Instruct","messages":[{"role":"system","content":"You are a helpful assistant."},{"role":"user","content":"What is the capital city of ${Country}? Don'\''t explain.\n<example 1>\nWhat is the capital city of USA?\nNew York\n</example 1>"}],"temperature":1,"max_tokens":10,"top_p":0.1}}]}'
```

### 3. Create a new Next.js Project

```bash
npx create-next-app@latest
cd (path/to/your/app)
```

### 4. Install jamaibase.

```bash
npm install jamaibase
```

### 5. Create `.env.local` file at the root of your project and add the keys:

```
NEXT_PUBLIC_JAMAI_BASEURL=http://api.jamaibase.com/
JAMAI_API_KEY=your_jamai_sk_api_key
JAMAI_PROJECT_ID=your_proj_id
```

### 6. Create a route handler to fetch data.

```tsx
// src/app/api/list-tables/route.ts

import JamAI from "jamaibase";
import { PageListTableMetaResponse } from "jamaibase/resources/gen_tables/tables";
import { NextResponse } from "next/server";

const jamai = new JamAI({
    baseURL: process.env.NEXT_PUBLIC_JAMAI_BASEURL!,
    apiKey: process.env.JAMAI_API_KEY,
    projectId: process.env.JAMAI_PROJECT_ID,
});

export async function GET() {
    try {
        let data: PageListTableMetaResponse = await jamai.listTables({
            table_type: "action",
        });
        return NextResponse.json(data);
    } catch (error: any) {
        console.error("Error fetching tables:", error.response);
        return NextResponse.json(
            { message: "Internal server error" },
            { status: 500 }
        );
    }
}
```

### 7. Then, in your Next.js component, you can fetch this data from the API route and render it

```tsx
// src/app/page.tsx

"use client";

import { PageListTableMetaResponse } from "jamaibase/resources/gen_tables/tables";
import { useEffect, useState } from "react";

export default function Home() {
    const [tableData, setTableData] = useState<PageListTableMetaResponse>();

    useEffect(() => {
        const fetchData = async () => {
            const response = await fetch("/api/list-tables");
            if (response.ok) {
                const data: PageListTableMetaResponse = await response.json();
                setTableData(data);
            } else {
                console.error("Failed to fetch data:", response.statusText);
            }
        };
        fetchData();
    }, []);
    return (
        <main className="flex min-h-screen flex-col  p-24">
            <div className="space-y-6">
                <h1 className="text-4xl">List of Tables</h1>
                <table className="min-w-full divide-y divide-gray-200">
                    <thead className="bg-gray-50">
                        <tr>
                            <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                Table ID
                            </th>
                            <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                Columns
                            </th>
                        </tr>
                    </thead>
                    <tbody className="bg-white divide-y divide-gray-200 text-black">
                        {tableData?.items.map((table) => (
                            <tr key={table.id}>
                                <td className="px-6 py-4 whitespace-nowrap">
                                    {table.id}
                                </td>
                                <td className="px-6 py-4 whitespace-nowrap">
                                    <ul className="space-y-2">
                                        {table.cols.map((column) => (
                                            <li key={column.id}>
                                                <span>{column.id}: </span>
                                                <span>{column.dtype}</span>
                                            </li>
                                        ))}
                                    </ul>
                                </td>
                            </tr>
                        ))}
                    </tbody>
                </table>
            </div>
        </main>
    );
}
```

### 8. Start the app

```
npm run dev
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.jamaibase.com/developer-reference/framework-integration/next-js.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
