#use api routes of both app, and page router
1 messages · Page 1 of 1 (latest)
Yes, you can definitely add Vercel AI to your existing Next.js application without moving all your pages to the api directory. Here's how you can do it:
-
Install Vercel AI SDK: First, you need to install the Vercel AI SDK in your project. You can do this using your favorite package manager. For example, if you're using
pnpm, you can install it by runningpnpm i ai(source (https://vercel.com/docs/integrations/openai)). -
Create a new Route Handler: You need to create a new Route Handler in your Next.js app that will interact with the AI's API to generate text completions. You can create a new file at
app/api/completion/route.tsand add the necessary code (source (https://vercel.com/guides/cohere-nextjs-vercel-ai-sdk)). -
Add Vercel AI SDK to your page: Inside your Next.js application, create a
page.tsxfile inside the App Router (app/) and add the necessary code to use the hooks and utilities provided by the Vercel AI SDK (source (https://vercel.com/guides/securing-ai-app-rate-limiting)). -
Create a Route Handler for OpenAI: Then, create a Route Handler to stream in your chat response from OpenAI. You can do this in the
api/chat/route.tsfile (source (https://vercel.com/guides/securing-ai-app-rate-limiting)).
Remember, if you're using the Pages Router, you can follow the instructions here (https://sdk.vercel.ai/docs/guides/frameworks/nextjs-pages) instead.
This way, you can add Vercel AI to your application without moving all your pages to the api directory.
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
@trail olive kapa.ai is still learning and improving, please let us know how it did by reacting below