#How to create a route handler and call it?
1 messages · Page 1 of 1 (latest)
Hi @lament mason. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
To create a route handler in Next.js and call it from a client component, follow these steps:
Step 1: Create a Route Handler
-
Create a new file in the
appdirectory. For example, createapp/api/completion/route.ts. -
Define the route handler using the appropriate HTTP method. Here is an example of a
POSTroute handler that interacts with an external API:
// app/api/completion/route.ts
import { StreamingTextResponse, CohereStream } from 'ai'
// IMPORTANT! Set the runtime to edge
export const runtime = 'edge'
export async function POST(req: Request) {
// Extract the `prompt` from the body of the request
const { prompt } = await req.json()
const body = JSON.stringify({
prompt,
model: 'command-nightly',
max_tokens: 300,
stop_sequences: [],
temperature: 0.9,
return_likelihoods: 'NONE',
stream: true
})
const response = await fetch('<https://api.cohere.ai/v1/generate',> {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${process.env.COHERE_API_KEY}`
},
body
})
// Extract the text response from the Cohere stream
const stream = CohereStream(response)
// Respond with the stream
return new StreamingTextResponse(stream)
}
Step 2: Call the Route Handler from a Client Component
- Use a data fetching library like
swroruseEffectto call the route handler from a client component. Here is an example usingfetchinside auseEffecthook:
import { useEffect, useState } from 'react'
function MyComponent() {
const [data, setData] = useState(null)
useEffect(() => {
async function fetchData() {
const response = await fetch('/api/completion', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ prompt: 'Your prompt here' })
})
const result = await response.json()
setData(result)
}
fetchData()
}, [])
return (
<div>
{data ? <pre>{JSON.stringify(data, null, 2)}</pre> : 'Loading...'}
</div>
)
}
export default MyComponent
### Additional Information
- **Route Handlers** are only available inside the `app` directory and are the equivalent of API Routes in the `pages` directory. You do not need to use both together (**source** (<https://nextjs.org/docs/app/building-your-application/routing/route-handlers>)).
- **Supported HTTP Methods** include `GET`, `POST`, `PUT`, `PATCH`, `DELETE`, `HEAD`, and `OPTIONS` (**source** (<https://nextjs.org/docs/app/api-reference/file-conventions/route>)).
For more detailed information, you can refer to the **Route Handlers documentation** (<https://nextjs.org/docs/app/building-your-application/routing/route-handlers>).
----------------------
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
----------------------