#How to fetch data from an api route in server page in app router?
1 messages · Page 1 of 1 (latest)
In the app directory of Next.js, you can fetch data from an API route using the fetch() function. This function is built on top of fetch() and async React Server Components. Here's an example of how you can use it:
export default async function Page() {
// This request should be cached until manually invalidated.
// Similar to `getStaticProps`.
// `force-cache` is the default and can be omitted.
const staticData = await fetch(`<https://...`,> { cache: 'force-cache' })
// This request should be refetched on every request.
// Similar to `getServerSideProps`.
const dynamicData = await fetch(`<https://...`,> { cache: 'no-store' })
// This request should be cached with a lifetime of 10 seconds.
// Similar to `getStaticProps` with the `revalidate` option.
const revalidatedData = await fetch(`<https://...`,> {
next: { revalidate: 10 },
})
return <div>...</div>
}
In this example, fetch() is used to make requests to an API. The cache option is used to specify how the request should interact with the server-side HTTP cache. For instance, force-cache means the request should be cached until manually invalidated, no-store means the request should be refetched on every request, and next: { revalidate: 10 } means the request should be cached with a lifetime of 10 seconds.
Please replace <https://...> with your actual API endpoint.
For more information, refer to the Next.js documentation on data fetching (https://nextjs.org/docs/app/building-your-application/data-fetching).
Please note that the code you provided is not listed in the knowledge sources, so I can't provide specific guidance on it.
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
@low gust kapa.ai is still learning and improving, please let us know how it did by reacting below
@final crest Can you show me in action how would you fetch this api file we have in app/api/events/category-region/route.ts: import getEventsByCategoryAndRegion from '@/app/actions/getEventsByCategoryAndRegion';
export const dynamic = 'force-dynamic';
export async function GET(request: Request) {
const url = new URL(request.url);
const category = url.searchParams.get('category');
const region = url.searchParams.get('region');
if (!category || !region) {
return new Response(
JSON.stringify({ error: 'Missing category or region parameter' }),
{
status: 400,
},
);
}
try {
const events = await getEventsByCategoryAndRegion(category, region);
return new Response(JSON.stringify(events), {
headers: { 'content-type': 'application/json' },
status: 200,
});
} catch (error: any) {
return new Response(JSON.stringify({ error: error.message }), {
status: 500,
});
}
}
To this page here. import getCurrentUser from '@/app/actions/getCurrentUser';
import ClientOnly from '@/app/components/ClientOnly';
import EmptyState from '@/app/components/EmptyState';
import EventCategoryRegion from './EventCategoryRegion';
interface IParams {
eventId?: string;
}
const EventCategoryPage = async ({ params }: { params: IParams }) => {
const currentUser = await getCurrentUser();
if (!event) {
return <EmptyState />;
}
return (
<ClientOnly>
<EventCategoryRegion event={event} currentUser={currentUser} />
</ClientOnly>
);
};
export default EventCategoryPage;
Let me check the knowledge base for you. One moment! :books:
To fetch data from the app/api/events/category-region/route.ts API route in your EventCategoryPage component, you can use the fetch function. Here's how you can modify your EventCategoryPage component to fetch data from the API route:
import getCurrentUser from '@/app/actions/getCurrentUser';
import ClientOnly from '@/app/components/ClientOnly';
import EmptyState from '@/app/components/EmptyState';
import EventCategoryRegion from './EventCategoryRegion';
interface IParams {
eventId?: string;
}
const EventCategoryPage = async ({ params }: { params: IParams }) => {
const currentUser = await getCurrentUser();
// Define the category and region parameters
const category = 'your-category';
const region = 'your-region';
// Fetch data from the API route
const response = await fetch(`/api/events/category-region?category=${category}®ion=${region}`, { cache: 'force-cache' });
const event = await response.json();
if (!event) {
return <EmptyState />;
}
return (
<ClientOnly>
<EventCategoryRegion event={event} currentUser={currentUser} />
</ClientOnly>
);
};
export default EventCategoryPage;
In this example, replace 'your-category' and 'your-region' with the actual category and region you want to fetch data for. The fetch function is used to make a GET request to the API route, and the response is converted to JSON and assigned to the event variable.
Please note that the fetch function is used with the cache: 'force-cache' option, which means the request should be cached until manually invalidated. This is similar to getStaticProps in Next.js.