---
sidebar_label: 'with Next.js and Vercel AI'
title: 'Get Started With NLUX, Next.js and Vercel AI'
---

import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';

# Get Started ― NLUX With Next.js And Vercel AI

Next.js is the most popular React framework for building web applications. Combined with Vercel AI SDK and NLUX, it
provides a perfect combination for building AI  assistants for your web application.

This guide will walk you through the steps to add NLUX with Vercel AI SDK to your Next.js app.

---

## 1. Create Your Next.js Application

Start by creating a new Next.js app using the following command:

<Tabs groupId="package" queryString>
    <TabItem value="npm" label="NPM">
        ```bash
        npx create-next-app@latest --ts --app my-ai-app
        ```
    </TabItem>
    <TabItem value="yarn" label="Yarn">
        ```bash
        yarn create next-app --ts --app my-ai-app
        ```
    </TabItem>
    <TabItem value="pnpm" label="PNPM">
        ```bash
        pnpm create next-app@latest --ts --app my-ai-app
        ```
    </TabItem>
</Tabs>

You can just accept the default options when prompted.

Then navigate to the newly created directory:

<Tabs groupId="package" queryString>
    <TabItem value="npm" label="NPM">
        ```bash
        cd my-ai-app
        ```
    </TabItem>
    <TabItem value="yarn" label="Yarn">
        ```bash
        cd my-ai-app
        ```
    </TabItem>
    <TabItem value="pnpm" label="PNPM">
        ```bash
        cd my-ai-app
        ```
    </TabItem>
</Tabs>

---

## 2. Install Dependencies

Next, install the `@nlux` dependencies:

<Tabs groupId="package" queryString>
    <TabItem value="npm" label="NPM">
        ```bash
        npm install @nlux/react @nlux/themes
        ```
    </TabItem>
    <TabItem value="yarn" label="Yarn">
        ```bash
        yarn add @nlux/react @nlux/themes
        ```
    </TabItem>
    <TabItem value="pnpm" label="PNPM">
        ```bash
        pnpm add @nlux/react @nlux/themes
        ```
    </TabItem>
</Tabs>

And the Vercel AI SDK dependencies:

<Tabs groupId="package" queryString>
    <TabItem value="npm" label="NPM">
        ```bash
        npm install ai @ai-sdk/openai @ai-sdk/react zod
        ```
    </TabItem>
    <TabItem value="yarn" label="Yarn">
        ```bash
        yarn add ai @ai-sdk/openai @ai-sdk/react zod
        ```
    </TabItem>
    <TabItem value="pnpm" label="PNPM">
        ```bash
        pnpm install ai @ai-sdk/openai @ai-sdk/react zod
        ```
    </TabItem>
</Tabs>

---

## 3. Configure OpenAI API key

In this guide, we are using OpenAI as the AI model provider.<br />
You are not limited to OpenAI, you can use any other AI model provider with Vercel AI SDK.

Let's start by getting a new API key from OpenAI.

1. If you don't have an account, go to the <a href="https://platform.openai.com/signup" target="_blank">OpenAI signup page</a> and create an account.
2. Go to the <a href="https://platform.openai.com/api-keys" target="_blank">API keys page</a>
3. Click the `Creat new secret key` button
4. Give your API key a name and click `Create secret key`, then copy the key to your clipboard
5. Create a `.env.local` file in your project root and add your OpenAI API Key. This key is used to authenticate
your application with the OpenAI service.

```
touch .env.local
```

6. Edit the `.env.local` file and add your OpenAI API Key:

```
OPENAI_API_KEY=your-openai-api-key
```

---

## 4. Create a Route Handler

Create a router handler in your Next.js app to handle the chatbot requests.<br />
The route file path should be `app/api/chat/route.ts`.<br />
Then add the following code:

```tsx
import { openai } from '@ai-sdk/openai';
import { streamText } from 'ai';

// Allow streaming responses up to 30 seconds
export const maxDuration = 30;

export async function POST(req: Request) {
    const { prompt } = await req.json();

    const result = await streamText({
        model: openai('gpt-4-turbo'),
        messages: [{
            role: 'user',
            content: prompt,
        }],
        async onFinish({ text, toolCalls, toolResults, usage, finishReason }) {
            // implement your own logic here, e.g. for storing messages
            // or recording token usage
        },
    });

    return result.toTextStreamResponse();
}
```

---

## 5. Add The NLUX UI Component

Now that you have a Route Handler that can query an LLM, it's time to set-up your NLUX UI component and
start interacting with your AI model.

Update your root page (`app/page.tsx`) with the following code to show a list of chat messages
and provide a user message input:

```tsx
'use client';
import {AiChat, ChatAdapter, StreamingAdapterObserver} from '@nlux/react';
import '@nlux/themes/nova.css';

export default function Chat() {
    const chatAdapter: ChatAdapter = { 
      
      streamText: async (prompt: string, observer: StreamingAdapterObserver) => {
        const response = await fetch('/api/chat', {
            method: 'POST',
            body: JSON.stringify({prompt: prompt}),
            headers: {'Content-Type': 'application/json'},
        });
        if (response.status !== 200) {
            observer.error(new Error('Failed to connect to the server'));
            return;
          }
      
          if (!response.body) {
            return;
          }
      
          // Read a stream of server-sent events
          // and feed them to the observer as they are being generated
          const reader = response.body.getReader();
          const textDecoder = new TextDecoder();
      
          while (true) {
            const { value, done } = await reader.read();
            if (done) {
              break;
            }
      
            const content = textDecoder.decode(value);
            if (content) {
              observer.next(content);
            }
          }
      
          observer.complete();
        }
    }

    return (
        <main className="flex min-h-screen flex-col items-center justify-between p-24">
            <div className="z-10 w-full max-w-3xl items-center justify-between font-mono text-sm lg:flex">
                <AiChat adapter={chatAdapter}/>
            </div>
        </main>
    );
}
```

Let's take a look at what is happening in this code:

1. We start by adding `'use client';` to the top of the file.<br />
    This tells the Next.js framework that **this file is intended to run on the client-side**.
1. We import `AiChat` from `@nlux/react` and the default theme `@nlux/themes/nova.css`.
2. We define a `chatAdapter` object that implements the interface `ChatAdapter`.<br />
    It contains on method `streamText` that handles chat responses streaming.
3. We render the `<AiChat />` component with the `chatAdapter` object.

---

## 6. Running Your Application and Configuring NLUX

1. Run the Development Server
2. Run npm run dev to start the development server.
3. Visit http://localhost:3000 to view your application.
4. Edit app/page.tsx (or pages/index.tsx) file and save it to see the updated result in your browser.

You can check the documentation and wide range of options available here:

* [Reference](https://docs.nlkit.com/nlux/reference/overview) — Documentation for all the components and configuration options.
* [Examples](https://docs.nlkit.com/nlux/examples) — Live editable examples to get you started quickly.

If you need help or have any questions, feel free to join our vibrant community on [Discord](https://discord.gg/SRwDmZghNB).
