
9 min read
How to Add an AI Chatbot to Your Nuxt Website with Aiduko
Build a chat page with Nuxt 4, Nuxt UI and the AI SDK. Connect it to Aiduko through a server route, stream answers from your website content and display source links.
Ask my AI assistantMichael Hoffmann
@mokkapps

I built Aiduko partly because I wanted chatbots for my own websites. The chat on this website now uses its API: my Nuxt server forwards visitor questions, and Aiduko searches my content and streams an answer back.
In my previous article, I explained how Aiduko works under the hood. In this article, I want to show you how to build the integration in your own Nuxt app, including a chat interface, streaming answers and source links.
We will use Nuxt 4, Nuxt UI 4 and the AI SDK. You don't need to create embeddings or run a vector database for this example. Aiduko handles indexing and retrieval.
Prepare Your Chatbot
First, create a chatbot in the Aiduko dashboard. Add your website to a knowledge base, select the pages the chatbot should use and wait for indexing to finish. Verify your domain to remove the restriction on how many of its pages can be indexed before verification.
Before writing any code, ask a few questions in the chatbot's playground. Pick questions your content actually answers and check the sources. If a page is missing there, changing the frontend won't fix the answer.
Next, open the chatbot's API tab and create an API key. Set a monthly token budget and a request limit that suit your application. Copy the key now, because it is only shown once. The Chat API documentation explains these settings.
Leave Show answer sources enabled in the behavior settings for this tutorial. Aiduko can also answer without displaying sources, but then it won't send the source parts our interface renders below.
Set Up the Nuxt App
Start with a Nuxt 4 application. If you already have one with Nuxt UI installed, add only the missing dependencies:
pnpm create nuxt aiduko-chat
cd aiduko-chat
pnpm add @nuxt/ui@4 tailwindcss ai@7 @ai-sdk/vue@4 zod@4
Enable Nuxt UI and declare the server configuration:
export default defineNuxtConfig({
css: ['~/assets/css/main.css'],
modules: ['@nuxt/ui'],
runtimeConfig: {
private: {
aidukoApiKey: '',
aidukoApiUrl: 'https://aiduko.com/api/v1/chat',
},
},
})
The API key belongs in private runtime configuration. Add it to your local .env file and keep that file out of version control:
NUXT_PRIVATE_AIDUKO_API_KEY=replace-with-your-aiduko-api-key
On your hosting platform, set the same environment variable for the running server. Nuxt reads .env during development; the built production server needs the environment variable supplied by your host.
Add the stylesheet imports required by Nuxt UI:
@import "tailwindcss";
@import "@nuxt/ui";
Wrap your pages in UApp:
<template>
<UApp>
<NuxtPage />
</UApp>
</template>
Forward Questions from Your Server
The browser sends questions to /api/chat in your app. That route adds the secret key and forwards the conversation to Aiduko. The browser never receives the key.
Create the server route:
import { z } from 'zod'
const messageSchema = z.object({
id: z.string().min(1).max(100),
parts: z.array(z.object({
text: z.string().min(1).max(4000),
type: z.literal('text'),
})).min(1).max(10),
role: z.enum(['user', 'assistant']),
})
const bodySchema = z.object({
id: z.string().regex(/^[\w-]{1,100}$/),
messages: z.array(messageSchema).min(1).max(40),
})
export default defineEventHandler(async (event) => {
const body = await readValidatedBody(event, bodySchema.parse)
const { aidukoApiKey, aidukoApiUrl } = useRuntimeConfig(event).private
if (!aidukoApiKey) {
throw createError({
statusCode: 503,
statusMessage: 'Chat is not configured.',
})
}
let response: Response
try {
response = await fetch(aidukoApiUrl, {
body: JSON.stringify(body),
headers: {
'accept': 'text/event-stream',
'authorization': `Bearer ${aidukoApiKey}`,
'content-type': 'application/json',
},
method: 'POST',
signal: AbortSignal.timeout(60_000),
})
}
catch {
throw createError({
statusCode: 502,
statusMessage: 'Chat is temporarily unavailable.',
})
}
if (!response.ok || !response.body) {
throw createError({
statusCode: response.status === 429 ? 429 : 502,
statusMessage: response.status === 429
? 'Chat limit reached. Please try again later.'
: 'Chat is temporarily unavailable.',
})
}
return sendWebResponse(event, new Response(response.body, {
headers: {
'cache-control': 'no-cache',
'content-type': 'text/event-stream',
'x-accel-buffering': 'no',
'x-vercel-ai-ui-message-stream': 'v1',
},
}))
})
The request contains the conversation ID and its messages. Aiduko uses the ID to group turns in the chatbot's conversation history. Each message has a role and an array of parts, rather than a single content string.
The Zod schema accepts text messages only. We will remove source and metadata parts before sending the next request, since those describe previous answers and aren't user input. The route rejects conversations with more than 40 messages and text parts longer than 4,000 characters instead of silently cutting them off.
Use native fetch here because we need the response body as a stream. Calling response.json() or response.text() would consume it before forwarding. sendWebResponse passes the stream to the browser, including the header that identifies the AI SDK UI message protocol.
The timeout bounds the upstream request, including reading its body. Errors before streaming starts become fixed messages; an interrupted response after streaming starts is handled by the client's error state.
Build the Chat Interface
The AI SDK's Vue integration manages the messages and reads the response stream. Nuxt UI's ChatMessages component displays the conversation and its loading state.
Create a client component with the complete chat interface:
<script setup lang="ts">
import { Chat } from '@ai-sdk/vue'
import { DefaultChatTransport, isTextUIPart } from 'ai'
import type { UIMessage } from 'ai'
const input = ref('')
let conversationId = crypto.randomUUID()
const chat = new Chat({
transport: new DefaultChatTransport({
api: '/api/chat',
prepareSendMessagesRequest: ({ messages }) => ({
body: {
id: conversationId,
messages: messages.map(message => ({
id: message.id,
parts: message.parts.filter(isTextUIPart),
role: message.role,
})),
},
}),
}),
})
const busy = computed(() =>
chat.status === 'submitted' || chat.status === 'streaming',
)
const conversationFull = computed(() => chat.messages.length >= 40)
function sources(message: UIMessage) {
return message.parts.filter(part => {
if (part.type !== 'source-url') return false
try {
const url = new URL(part.url)
return url.protocol === 'https:' || url.protocol === 'http:'
}
catch {
return false
}
}).filter(part => part.type === 'source-url')
}
function submit() {
const text = input.value.trim()
if (!text || busy.value || conversationFull.value) return
input.value = ''
void chat.sendMessage({ text })
}
function reset() {
chat.messages = []
conversationId = crypto.randomUUID()
chat.clearError()
input.value = ''
}
</script>
<template>
<section class="mx-auto flex max-w-3xl flex-col gap-6 p-6">
<div class="flex items-center justify-between gap-4">
<h1 class="text-2xl font-semibold text-highlighted">
Ask about this website
</h1>
<UButton
color="neutral"
variant="outline"
:disabled="busy"
@click="reset"
>
New chat
</UButton>
</div>
<p v-if="!chat.messages.length" class="text-muted">
Ask a question about the content of this website.
</p>
<UChatMessages :messages="chat.messages" :status="chat.status">
<template #content="{ message }">
<template v-for="(part, index) in message.parts" :key="index">
<p v-if="part.type === 'text'" class="whitespace-pre-wrap">
{{ part.text }}
</p>
</template>
<ul
v-if="message.role === 'assistant' && sources(message).length"
aria-label="Answer sources"
class="mt-3 space-y-2"
>
<li v-for="source in sources(message)" :key="source.sourceId">
<a
:href="source.url"
target="_blank"
rel="noopener noreferrer"
class="text-primary underline"
>
[{{ source.sourceId }}] {{ source.title || source.url }}
</a>
</li>
</ul>
</template>
</UChatMessages>
<p v-if="chat.error" role="alert" class="text-error">
The answer could not be completed. Please start a new chat and try again.
</p>
<p v-if="conversationFull" role="status" class="text-muted">
This conversation is full. Start a new chat to ask more questions.
</p>
<form class="flex items-end gap-3" @submit.prevent="submit">
<div class="min-w-0 flex-1">
<label for="chat-question" class="mb-2 block text-sm">
Your question
</label>
<UTextarea
id="chat-question"
v-model="input"
:maxlength="4000"
:disabled="busy || conversationFull || !!chat.error"
class="w-full"
autoresize
/>
</div>
<UButton
type="submit"
:loading="busy"
:disabled="!input.trim() || conversationFull || !!chat.error"
>
Send
</UButton>
</form>
</section>
</template>
DefaultChatTransport sends requests to our own server route. Its prepareSendMessagesRequest callback keeps the conversation ID and forwards only text parts. Without that filtering, the previous assistant answer would also send its source parts back to the text-only route.
The Chat instance updates messages as text arrives. Its status moves from submitted to streaming and then to ready. We disable the input while an answer is running to avoid overlapping requests in the same conversation.
This example renders answer text with Vue interpolation. Markdown syntax such as bold text remains visible, but HTML isn't interpreted. If you add a Markdown renderer later, configure it for untrusted model output rather than inserting the answer with v-html.
Aiduko's citation markers, for example [2], match the sourceId of a source-url part. The list below each answer displays that number next to its link. These are the source parts supplied by Aiduko, not URLs extracted from generated text. The component allows only HTTP and HTTPS links.
This tutorial indexes a website. Uploaded documents use source-document parts instead, because a private file has no public page URL. To support them, add a separate display for the document title instead of inventing a download link.
Finally, render the component on a page:
<template>
<AidukoChat />
</template>
The .client.vue suffix keeps the chat instance in the browser. Opening a new chat clears the visible messages and changes the conversation ID so future questions form a separate conversation in Aiduko.
Try the Integration
Start the development server and open /chat:
pnpm dev
Ask a question about an indexed page. You should see the answer arrive progressively, followed by numbered source links. Open those links and check that the pages support the answer.
Then ask a follow-up question that refers to the previous answer. The request sends the conversation history, so Aiduko can use that context. Also ask something outside your content and check how the chatbot responds when it has no useful source.
To check failure handling, temporarily replace the local API key with an invalid value and restart the server. The interface should display the error message and let you start a new chat. Restore your real key afterwards. In your browser's Network panel, requests should go to /api/chat; the Aiduko bearer token should never appear there.
Before Making the Chat Public
The API key's request limit applies to all visitors using that key. Add a separate visitor limit to your Nuxt route before exposing it publicly, so a single visitor cannot consume the shared budget. For an app with accounts, use the authenticated user ID. For an anonymous site, an IP-based limit needs a shared store and proxy settings that match your hosting setup. An in-memory counter resets on restart and won't coordinate multiple server instances.
Also set a request body size limit at your server or reverse proxy. Zod validates the parsed messages; it doesn't prevent a large body from being received first. For a private knowledge base, require authentication on your route and check that the visitor may access that content.
This short example uses a fixed upstream timeout. In production, also abort the upstream request when the visitor disconnects and verify that your hosting proxy forwards streaming responses without buffering them. Monitor rejected requests: Aiduko returns 429 for request limits and exhausted token budgets, so retrying immediately won't always help. Its API reference documents the error codes.
Conclusion
For my own websites, I wanted control over the chat interface while using the same indexing and answer service. This integration lets me keep the Nuxt components and server route in each app and manage the knowledge in Aiduko.
The remaining work is specific to the website: visitor limits, access rules and questions that test whether the indexed content is enough. I would start with those questions before spending more time on the chat's appearance.


How I Replaced Revue With a Custom-Built Newsletter Service Using Nuxt 3, Supabase, Serverless, and Amazon SES

Why I Built Aiduko, an AI Chatbot for Your Content, and How It Works
