Skip to main content
Version: v2.x

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:

npx create-next-app@latest --ts --app my-ai-app

You can just accept the default options when prompted.

Then navigate to the newly created directory:

cd my-ai-app

2. Install Dependencies

Next, install the @nlux dependencies:

npm install @nlux/react @nlux/themes

And the Vercel AI SDK dependencies:

npm install ai @ai-sdk/openai @ai-sdk/react zod

3. Configure OpenAI API key

In this guide, we are using OpenAI as the AI model provider.
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 OpenAI signup page and create an account.
  2. Go to the API keys page
  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
  1. 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.
The route file path should be app/api/chat/route.ts.
Then add the following code:

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:

'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.
    This tells the Next.js framework that this file is intended to run on the client-side.
  2. We import AiChat from @nlux/react and the default theme @nlux/themes/nova.css.
  3. We define a chatAdapter object that implements the interface ChatAdapter.
    It contains on method streamText that handles chat responses streaming.
  4. 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 — Documentation for all the components and configuration options.
  • 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.