Using AI Vercel SDK (AI SDK Core) with Next.js and App Router

@shaaddev

In this article, we will be going through how to setup the AI Vercel SDK with App Router and the Stream Chat Completion Function. With this, there will be no in depth explanation and only a step by step guide

Next.js and App Router

Setting Up the Development Environment

If you already know how to this part then you can skip to the integration of the AI SDK. Also, make sure to have Node Package Manager installed on your device if you haven't already.

  1. Create Next.js Project

Don't worry to much about bun, you can use npm, yarn, or pnpm.

  1. Install additional dependencies

You can use any provider here such as Google or AWS Bedrock like so

To see more available providers click on the link below:

AI SDK Providers

(Optional) The styling being used here will be Shadcn, you don't necessarily need to use this but it'll be faster to speed up the process.

  1. Create an environment variable file

Create a new file called .env.local in the root directory and this is where you'll store various API Keys. As said before, you can use any provider but for this project, we will be using Google as this is the free option.

  1. Creating Server Action

We will be implementing a continueConversation function that will insert the user's message into the conversation and stream back the new message.

Create a new file app/actions.tsx and add the following:

Yep, it's that simple!

  1. Creating the Chatbot Component

Create a new Folder called components if you don't have one already and create a new file called components/chatbot.tsx and add the following. Don't worry, we'll be calling this component in app/page.tsx later on.

Now let's navigate to app/page.tsx

  1. Test the Application

Once you added your own styling and everything is setup properly, let's start up the development server.

and navigate to http://localhost:3000

Conclusion

And yeahhhh, if everything goes well then you are now able to create or integrate AI into your web applications. Feel free to hit me up if anything goes wrong and I will try my best to either help you out or edit this blog for any updates made by the developers at Vercel.