Next.js Discord

Discord Forum

What is the correct way to use API routes?

Answered
American Shorthair posted this in #help-forum
Open in Discord
American ShorthairOP
I'm new to Next.js and I have recently started a small learning project in my spare time using Next.js 14 & App Router. As you'll see from the title, I am wondering what is the best wat to use API routes in Next.js?

I've read through https://nextjs.org/docs/app/building-your-application/routing/route-handlers, https://nextjs.org/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating and https://nextjs.org/docs/app/building-your-application/data-fetching/patterns, but I am still unsure.

I currently have a route handler (api/random-image/route.ts) that looks like this:

import {NextRequest, NextResponse} from "next/server";

export async function GET (request: NextRequest){
const res = await fetch(${process.env.API_BASE_URL}breeds/image/random)
const data = await res.json()

return NextResponse.json({ data })
}

And a page.tsx (random-image/page.tsx) file that looks like this:

import Image from 'next/image'

async function getRandomImage() {
const res = await fetch(${process.env.BASE_URL}api/random-image)

if (!res.ok) {
throw new Error('Failed to fetch data')
}

return res.json()
}

export default async function RandomImage() {
const randomImage = await getRandomImage();
return (
<main>
<a href="/">back home</a>
<div className="w-full">
<Image src={randomImage.data.message} alt={randomImage.data.message} fill={true}/>
</div>
</main>
)
}

I also have a .env.local file with my environment variables.

Am I using the API route correctly or am I adding an unnecessary layer of abstraction?

Some problems that I have faced so far:
- In page.tsx, process.env.BASE_URL returns undefined unless I set the BASE_URL environment variable in next.config.js. It returns undefined when I set it within my .env.local file.
- Again in page.tsx, in the fetch method, if I set the url to /loapi/random-image I get the error in the attached image.

Any help would be greatly appreciated!

1 Reply

@American Shorthair I'm new to Next.js and I have recently started a small learning project in my spare time using Next.js 14 & App Router. As you'll see from the title, I am wondering what is the best wat to use API routes in Next.js? I've read through https://nextjs.org/docs/app/building-your-application/routing/route-handlers, https://nextjs.org/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating and https://nextjs.org/docs/app/building-your-application/data-fetching/patterns, but I am still unsure. I currently have a route handler (api/random-image/route.ts) that looks like this: import {NextRequest, NextResponse} from "next/server"; export async function GET (request: NextRequest){ const res = await fetch(`${process.env.API_BASE_URL}breeds/image/random`) const data = await res.json() return NextResponse.json({ data }) } And a page.tsx (random-image/page.tsx) file that looks like this: import Image from 'next/image' async function getRandomImage() { const res = await fetch(`${process.env.BASE_URL}api/random-image`) if (!res.ok) { throw new Error('Failed to fetch data') } return res.json() } export default async function RandomImage() { const randomImage = await getRandomImage(); return ( <main> <a href="/">back home</a> <div className="w-full"> <Image src={randomImage.data.message} alt={randomImage.data.message} fill={true}/> </div> </main> ) } I also have a .env.local file with my environment variables. Am I using the API route correctly or am I adding an unnecessary layer of abstraction? Some problems that I have faced so far: - In page.tsx, process.env.BASE_URL returns undefined unless I set the BASE_URL environment variable in next.config.js. It returns undefined when I set it within my .env.local file. - Again in page.tsx, in the fetch method, if I set the url to `/loapi/random-image` I get the error in the attached image. Any help would be greatly appreciated!
Answer